for vs forEach

JavaScript performance comparison

Revision 136 of this test case created by Sander Elias

Info

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 code

<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
  }
  console.log(x) //do something with X!
};
</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
forEach
values.forEach(add);
pending…
for loop, simple, cached length
var x = 0,
  l = values.length;
for (x = 0; x < l; x += 1) {
  add(values[x]);
}
console.log(x)
pending…
While loop, same as prototype
var l = values.length,
  x = 0,
  callback = add;
while (x < l) {
  callback(values[x], x, values);
  x += 1
}
console.log(x)
pending…
While loop, same as prototype but without callback!
var l = values.length,
  x = 0;
while (x < l) {
  add(values[x]);
  x += 1
}
console.log(x)
pending…
own iterpertation of forEach
values.seForEach(add);
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