Loops

JavaScript performance comparison

Revision 126 of this test case created by Mac

Preparation code

<script>
  var arr = [ 120 ];
  var obj = {};
  for( var i = 0, len = arr.length; i < len; i++ ) {
    obj[ i ] = null;
  }

  function advancedLoop( data, callback ) {
    for( var i = 0, j; undefined !== ( j = arr[ i ]); i++ ) {
      callback( j );
    };
  }
</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
1) while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
  arr[i];
  i++;
};
pending…
2) while loop that imitates a for loop, caching the length
var i = 0,
    len = arr.length;
while (i < len) {
  arr[i];
  i++;
};
pending…
3) Reverse while loop
var i = arr.length;
while (i--) {
  arr[i];
};
pending…
4) Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
  arr[i];
};
pending…
5) Reverse do … while loop
var i = arr.length;
do {
  arr[i];
} while (i--);
pending…
6) Reverse for loop
for (var i = arr.length; i--;) {
  arr[i];
};
pending…
7) Old ’n’ busted for loop
for (var i = 0; i < arr.length; ++i) {
  arr[i];
};
pending…
8) Old ’n’ busted for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
  arr[i];
};
pending…
9) Cool guy loop
for (var i = -1; ++i < arr.length;) {
  arr[i];
};
pending…
10) Cool guy loop, caching the length
for (var i = -1, len = arr.length; ++i < len;) {
  arr[i];
};
pending…
11) Native Array#forEach implementation
arr.forEach(function(x) {
  x;
});
pending…
12) Native Array#forEach implementation with named function
function foo(x) {
  x;
};
arr.forEach(foo);
pending…
13) For In Array
for (i in arr) {
  arr[i]
}
pending…
14) For In Object
for (i in obj) {
  obj[i]
}
pending…
15) For loop with assignation as condition
for (var i = 0, j; undefined !== (j = arr[i]); i++) {
  j;
};
pending…
16) For loop with assignation as condition and with callback
advancedLoop(arr, function(i) {
  i;
});
pending…
17) Old ’n’ busted for loop, var outside loop
var len = arr.length;
for( var i = 0; i < len; ++i ) {
  arr[ i ];
};
pending…
18) Reverse for loop, var outside loop
var len = arr.length;
for( var i = len; i--; ) {
  arr[ 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