For Loop vs. Optimized For Loop

JavaScript performance comparison

Revision 27 of this test case created

Info

A speed comparison between for loops.

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 Loop
var anchors = document.getElementsByTagName("a");

for (i = 0; i < anchors.length; i++) {
  anchors[i].style.color = "red";
}
pending…
Optimized For Loop
var anchors = document.getElementsByTagName("a");

for (var i = anchors.length - 1; i >= 0; i -= 1) {
  anchors[i].style.color = "red";
}
pending…
get length outside of loop
var anchors = document.getElementsByTagName("a"),
    i,
    _anchorLength;
_anchorLength = anchors.length

for (i = 0; i < _anchorLength; i++) {
  anchors[i].style.color = "red";
}
pending…
Declaration in For Loop
var anchors = document.getElementsByTagName("a");
var len=anchors.length
for (var i = 0; i < len; i++) {
  anchors[i].style.color = "red";
}
pending…
var anchors = document.getElementsByTagName("a");

for (var i = anchors.length; i--;) {
  anchors[i].style.color = "red";
}
pending…
For Loop +=
var anchors = document.getElementsByTagName("a"),
    i,
    _anchorLength;

for (i = 0, _anchorLength = anchors.length; i < _anchorLength; i += 1) {
  anchors[i].style.color = "red";
}
pending…
PreIncrement For Loop
var anchors = document.getElementsByTagName("a"),
    i,
    _anchorLength;

for (i = 0, _anchorLength = anchors.length; i < _anchorLength; ++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:

0 comments

Add a comment