for vs forEach

JavaScript performance comparison

Revision 403 of this test case created by jKey

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
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 + push (save, but reverse ary)
var buff = [],
  i;

while (values.length) {
  sum += i = values.pop();
  buff.push(i);
}

values = buff;
pending…
whlile by 3
// for sum only

var i = values.length;

while (i >= 0) {
  sum += values[--i];
  sum += (values[--i] || 0);
  sum += (values[--i] || 0);
}
pending…
reduce
sum = values.reduce(rsum);
pending…
Copy + pop
var buff = [].concat(values),
  i;

while (values.length) {
  sum += i = values.pop();

}

values = buff;
pending…
for of
(function(){

  "use strict";
  for (let value of values) {
    add(value);
  }
})();
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