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

JavaScript performance comparison

Test case created by Craig

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…

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:

1 comment

Samori Gorse commented :

The test is tampered and misleading. for and while examples do not cache nodes.length, which has been proven significantly quicker.

Add a comment