for vs forEach

JavaScript performance comparison

Revision 87 of this test case created by BrunoLM

Info

Is it faster to use the native forEach or just loop with for?

Preparation code

<script>
  var i, values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
   values[i] = i;
  }
 
  function add(val, index) {
   sum += val + index;
  }

   Array.prototype.CustomForEach = function(fn) {
       for (var i = 0, n = this.length; i < n; ++i)
           fn(this[i], i);
   };

   Array.prototype.CustomForEachCacheRef = function(fn) {
       var a = this;
       for (var i = 0, n = a.length; i < n; ++i)
           fn(a[i], i);
   };
</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
for (var i = 0, n = values.length; i < n; ++i) {
  add(values[i], i);
}
pending…
CustomForEach
values.CustomForEach(add);
pending…
CustomForEachCacheRef
values.CustomForEachCacheRef(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