Array.forEach vs. for-loop --> scaling (v10)

Revision 10 of this benchmark created on


Description

Was trying to come up with some sort of syntactic sugar that comes closer to the prettiness of Array.forEach(fn) syntax but with the performance closer to native for-loop.

Clearly "forEach2" is not it, yet. It's currently terribly worse than either a for-loop or even forEach. :)

It's mainly because for-in-loop performance is terrible compared to for-loop: http://jsperf.com/for-loop-vs-for-in-loop

Preparation HTML

<script>
  Array.prototype.forEach2 = function(fn, thisObj) {
   for (var i = 0, len = this.length; i < len; i++) {
   fn.call(thisObj, void 0, 0, this, k);
   }
  };
  
  var arr = ['1', true, false, "", void 0, null, 2, 18.5936];
  
  delete(arr[3]);
  
  var arr2 = arr.slice();
  
  for (var j = 0; j < 500; j++) {
   arr2.push(Math.round(Math.random()));
  }
  
  var arr3 = arr2.slice();
  
  for (var m = 0; m < 5000; m++) {
   arr3.push(Math.round(Math.random()));
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
big array: native forEach
arr3.forEach(function(v, i, a) {
  v;
});
ready
big array: native for-loop
for (var i = 0, len = arr3.length, v; i < len; i++) {
  v = arr3[i];
}
ready
big array: forEach2 + native for-loop
arr3.forEach2(function(v, i, a, k) {
  for (i in k) {
    v = a[i];
  }
});
ready
big array: reverse native for-loop
for (var i = arr3.length; i--;) {
  v = arr3[i];
}
ready

Revisions

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