for vs forEach (v295)

Revision 295 of this benchmark created by bob on


Setup

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
  }

Teardown



            i = 0;
  value = 0;
  length = 0;
  values = [];
  sum = 0;
        
  

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
for loop, cached length
length = values.length;
for (i = 0; i < length; i++) {
    sum += values[i];
}
ready
for loop, assignment condition
for (i = 0; (value = values[i]) !== undefined; i++) {
    sum += value;
}
ready
forEach without cache
values.forEach(function (val) {
    sum += val;
});
ready
personal foreach
my_for_each(values, function (v) {sum+=v} )
ready
perso2 (more general)
my_for_each2(values, function (v) {sum+=v} )
ready
perso3
my_for_each3(values, function (v) {sum+=v} )
ready
perso4 as in the specs (by use)
my_for_each4(values, function (v) {sum+=v})
ready
perso5
my_for_each5(values, function (v) {sum+=v})
ready

Revisions

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