for vs forEach (v138)

Revision 138 of this benchmark created by Sander Elias on


Description

Is it faster to use the native forEach or just loop with for? if I use my own foreach, will it be faster then the native one?

Preparation HTML

<script>
  var i, values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
   values[i] = i;
  }
  
  function add(val) {
   sum += val;
  }
Array.prototype.seForEach = function(callback) {
  var a=this,l = a.length, x=0;
  while (x<l) {
     callback(a[x], x, a);
     x += 1
  }  
};
</script>

Setup

sum = 0;

Teardown


    console.log(sum)
  

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
for loop, simple, cached length
var x = 0,
  l = values.length;
for (x = 0; x < l; x += 1) {
  add(values[x]);
}
ready
While loop, same as prototype
var l = values.length,
  x = 0,
  callback = add;
while (x < l) {
  callback(values[x], x, values);
  x += 1
}
ready
While loop, same as prototype but without callback!
var l = values.length,
  x = 0;
while (x < l) {
  add(values[x]);
  x += 1
}
ready
own iterpertation of forEach
values.seForEach(add);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.