for vs forEach

JavaScript performance comparison

Revision 87 of this test case created by BrunoLM

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 CCBot 2.0.0 / Other 0.0.0
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.

0 Comments