forEach() compared to for() and while()

JavaScript performance comparison

Revision 2 of this test case created

Info

Comparison of different methods of looping through nodelists

Preparation code

<div>
</div>
<script>
  var nodes = document.getElementsByTagName("DIV");
  var x;
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
forEach
[].forEach.call(nodes, function(item) {
  x = item;
});
pending…
for
for (var i = 0; i < nodes.length; i++) {
  x = nodes[i];
}
pending…
while
var i = 0;
while (i < nodes.length) {
  x = nodes[i];
  i++;
}
pending…
while() backwards
var i = nodes.length;
while (i--) {
  x = nodes[i];
}
pending…
for() with cached nodes.length
for (var i = 0, max = nodes.length; i < max; i++) {
  x = nodes[i];
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

Hendrik Runte commented :

I added the test "for() with cached nodes.length" which saves even more time by caching the nodes.length value into another local variable. It prevents the browser from looking up the nodes.length on every iteration. Note that this should not be applied to iterations that change the nodes.length during the iteration (which might be a bad design).

This seems to be the fastest on Safari and Firefox.

Regards, Hendrik.

jose antonio rivas commented :

In the most of the languages ++i it's faster than i++ this is true in js?

Add a comment