Loops

JavaScript performance comparison

Revision 210 of this test case created by

Preparation code

<script>
   var i,
        arr = [],
        sum = 0
    
    
    for (i = 0; i < 10000; i++) {
        arr[i] = Math.random();
    }
</script>
      
<script>
Benchmark.prototype.setup = function() {
  Array.prototype.my_forEach = function(f) {
    for (var k = -1, m = this.length; ++k < m;)
      if (k in this) f(this[k], k, this)
  }
  
  var my_forEach = function(A, f) {
    for (var k = 0, m = A.length; k < m; k++)
      if (k in A) f(A[k], k, A)
  }

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
  sum += arr[i];
  i++;
};
pending…
while loop that imitates a for loop, caching the length
var i = 0,
  len = arr.length;
while (i < len) {
  sum += arr[i];
  i++;
};
pending…
Reverse while loop
var i = arr.length;
while (i--) {
  sum += arr[i];
};
pending…
Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
  sum += arr[i];
};
pending…
Reverse do … while loop
function wi(arr, cb) {
  var i = arr.length;
  while (i-- > 0) {
    cb(arr[i]);
  };
}

wi(arr, function(x) {
  sum += x;
});
pending…
Reverse for loop
for (var i = arr.length; i--;) {
  sum += arr[i];
};
pending…
Old ’n’ busted for loop
function foreach(array, cb) {
  var i = 0,
    len = array.length;

  for (; i < len; ++i) cb(array[i]);
}

foreach(arr, function(x) {
  sum += x;
})
pending…
Old ’n’ busted for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
  sum += arr[i];
};
pending…
Cool guy loop
for (var i = -1; ++i < arr.length;) {
  sum += arr[i];
};
pending…
Cool guy loop, caching the length
for (var i = -1, len = arr.length; ++i < len;) {
  sum += arr[i];
};
pending…
Native Array#forEach implementation
arr.forEach(function(x) {
  sum += x;
});
pending…
Native Array#forEach implementation with named function
function foo(x) {
  sum += x;
};
arr.forEach(foo);
pending…
perso implement
arr.my_forEach(function(x) {
  sum += x;
});
pending…
perso2
my_forEach(arr, function(x) {
  sum += 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.

0 Comments