For Loop vs. Optimized For Loop

JavaScript performance comparison

Revision 22 of this test case created by tomByrer

Info

A speed comparison between for loops that deal with the DOM.

v22; cloned v21 & labeled last test.

Preparation code

<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>

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
Customary For
var anchors = document.getElementsByTagName("a");
var total = anchors.length;
for (i = 0; i < total; i++) {
  anchors[i].style.color = "red";
}
pending…
Array.prototype.map.call
var anchors = document.getElementsByTagName("a");
Array.prototype.map.call(anchors, function(anchor){
  anchor.style.color = "red";
});
pending…
Optimized While
var anchors = document.getElementsByTagName("a"),
    i = anchors.length;

while (i--) {
  anchors[i].style.color = "red";
}
pending…
Optimize Do While
var anchors = document.getElementsByTagName("a"),
    i = anchors.length - 1;

do {
  anchors[i].style.color = "red";
}
while (i--);
pending…
length backwards
var anchors = document.getElementsByTagName("a");
for(var i = anchors.length; i--;) {
  anchors[i].style.color = "red";
}
 
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

tomByrer (revision owner) commented :

[Array.prototype.map](http://kangax.github.io/es5-compat-table/#Array.prototype.map fails in IE8); "Optimize Do While" is fastest with "length backwards" just behind.

Add a comment