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

JavaScript performance comparison

Revision 5 of this test case created by DanMan

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++];
}
pending…
while() backwards
var i = nodes.length;
while (i--) {
 x = nodes[i];
}
pending…
for by index
for (var i = 0; nodes[i]; i++) {
 x = nodes[i];
}
pending…
for by index with label
for (var i = 0, item; item=nodes[i]; i++) {
 x = item;
}
pending…
while by index
var i = 0;
while (nodes[i]) {
 x = nodes[i++];
}
pending…
while by index with label
var i = 0, item;
while (item=nodes[i++]) {
 x = item;
}
pending…
for cached
for (var i = 0, l = nodes.length; i < l; i++) {
 x = nodes[i];
}
pending…
while cached
var i = 0, l = nodes.length;
while (i < l) {
 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:

0 comments

Add a comment