for vs forEach

JavaScript performance comparison

Revision 221 of this test case created by David Mulder

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
    var i, values = [],
        sum = 0;
    for (i = 0; i < 10; i++) {
     values[i] = i;
    }
    
    function add(val) {
     sum += val;
    }
  
    function rsum(previousSum, currentItem) {
      return previousSum + currentItem;
    }

};
</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
forEach anon bound
values.forEach((function(e){
    sum += e;
}).bind(this));
pending…
forEach
values.forEach(add);
pending…
for loop, simple
for (i = 0; i < values.length; i++) {
 add(values[i]);
}
pending…
for loop, cached length
var len = values.length;
for (i = 0; i < len; i++) {
 add(values[i]);
}
pending…
for loop, reverse
for (i = values.length - 1; i >= 0; i--) {
 add(values[i]);
}
pending…
forEach more local
(function() {
 var sum = 0;
 values.forEach(function(val) {
  sum += val;
 });
})();
pending…
While Reverse Loop
var i = values.length;
while (i--) {
  sum += values[i];
}
pending…
some
values.some(add);
pending…
some with anonymous fn
values.some(function(e){
   sum += e
});
pending…
every with anonymous
values.every(function(e){
    sum += e;
    return true;
});
pending…
pop
//
/*
var vcheck = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (var i = 0; i < vcheck.length; i++) {
    if (values[i] === vcheck[i]) alert('this is wrong!!!');
}
*/

// if ary no longer needed only

while(values.length) {
    sum += values.pop();
}
pending…
for pop in condition
for (var i; i = values.pop();) sum += i
pending…
pop with slice (for short arrays)
var buff = values.slice(0, values.length);

while(buff.length) {
    sum += buff.pop();
}
pending…
reduce
sum = values.reduce(rsum);
pending…
shift
// if ary no longer needed only

while(values.length) {
    sum += values.shift();
}
pending…
forEach anon
values.forEach(function(e){
    sum += e;
});
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