for vs forEach

JavaScript performance comparison

Revision 295 of this test case created by bob

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var i,
      value,
      length,
      values = [],
      sum = 0,
      context = values;
  
  
  for (i = 0; i < 10000; i++) {
      values[i] = Math.random();
  }
  
  function add(val) {
      sum += val;
  }
  
  function my_for_each(A, f)
  {
  
      for(var k = 0, m = A.length; k<m; k++)
           f(A[k], k, A)
  }
  
  
  function my_for_each2(A, f)
  {
  
      for(var k = 0, m = A.length; k<m; k++)
          if(k in A) f(A[k], k, A)
  }
  function my_for_each3(A, f, that)
  {
  
      for(var k = 0, m = A.length; k<m; k++)
          if(k in A) {
              if (that) f.call(that, A[k], k, A)
              else f(A[k], k, A)
          }
  }
  
  function my_for_each4(A, f, that)
  {
  
      for(var k = 0, m = A.length; k<m; k++)
          if(k in A) {
              f.call(that, A[k], k, A)
          }
  }
  var GLOBAL = function () {return this} ();
  var emptyy = {};
  function my_for_each5(A, f, that)
  {
     // if (!that) that = GLOBAL;
      if (!that) that = emptyy;
      var id = '_' + Math.random();
      that[id] = f;
      for(var k = 0, m = A.length; k<m; k++)
          if(k in A) {
              that[id](A[k], k, A)
          }
      delete that[id]; //optional and not always better for perfs
  }

};

Benchmark.prototype.teardown = function() {
  i = 0;
  value = 0;
  length = 0;
  values = [];
  sum = 0;

};
</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, cached length
length = values.length;
for (i = 0; i < length; i++) {
    sum += values[i];
}
pending…
for loop, assignment condition
for (i = 0; (value = values[i]) !== undefined; i++) {
    sum += value;
}
pending…
forEach without cache
values.forEach(function (val) {
    sum += val;
});
pending…
personal foreach
my_for_each(values, function (v) {sum+=v} )
pending…
perso2 (more general)
my_for_each2(values, function (v) {sum+=v} )
pending…
perso3
my_for_each3(values, function (v) {sum+=v} )
pending…
perso4 as in the specs (by use)
my_for_each4(values, function (v) {sum+=v})
pending…
perso5
my_for_each5(values, function (v) {sum+=v})
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