Loops

JavaScript performance comparison

Revision 142 of this test case created

Preparation code

<script>
  var arr = [];
  for (var i = 0; i < 1000; i++) {
   arr.push(i);
  }

  function someFunc(i) {
    return i * 8 / 4 + 9;
  }
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
 someFunc(arr[i]);
 i++;
};
pending…
while loop that imitates a for loop, caching the length
var i = 0,
    len = arr.length;
while (i < len) {
 someFunc(arr[i]);
 i++;
};
pending…
Reverse while loop
var i = arr.length;
while (i--) {
 someFunc(arr[i]);
};
pending…
Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
 someFunc(arr[i]);
};
pending…
Reverse do … while loop
var i = arr.length;
do {
 someFunc(arr[i]);
} while (i--);
pending…
Reverse for loop
for (var i = arr.length; i--;) {
 someFunc(arr[i]);
};
pending…
Old ’n’ busted for loop
for (var i = 0; i < arr.length; ++i) {
 someFunc(arr[i]);
};
pending…
Old ’n’ busted for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
 someFunc(arr[i]);
};
pending…
Cool guy loop
for (var i = -1; ++i < arr.length;) {
 someFunc(arr[i]);
};
pending…
Cool guy loop, caching the length
for (var i = -1, len = arr.length; ++i < len;) {
 someFunc(arr[i]);
};
pending…
Native Array#forEach implementation
arr.forEach(function(x) {
 someFunc(x);
});
pending…
Native Array#forEach implementation with named function
function foo(x) {
 someFunc(x);
};
arr.forEach(foo);
pending…
item = arr[i]
for (var i = 0, x; x = arr[i]; i++) {
  someFunc(x);
}
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

200_success commented :

The x = item[i] test in Revision 142 is a no-op. The first thing it does is set x = 0, then it immediately terminates the loop.

Add a comment