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

Revision 3 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) {
   var k = {};
   for (var i = 0, len = this.length; i < len; i++) this.hasOwnProperty(i) && (k[i] = 0);
   fn.call(thisObj, void 0, 0, this, k);
   return this;
  };
  
  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
small array: native forEach
arr.forEach(function(v, i, a) {
 v;
});
ready
medium array: native forEach
arr2.forEach(function(v, i, a) {
 v;
});
ready
big array: native forEach
arr3.forEach(function(v, i, a) {
 v;
});
ready
small array: native for-loop
for (var i = 0, len = arr.length, v; i < len; i++) {
 v = arr[i];
}
ready
medium array: native for-loop
for (var i = 0, len = arr2.length, v; i < len; i++) {
 v = arr2[i];
}
ready
big array: native for-loop
for (var i = 0, len = arr3.length, v; i < len; i++) {
 v = arr3[i];
}
ready
small array: forEach2 + native for-loop
arr.forEach2(function(v, i, a, k) {
 for (i in k) {
  v = a[i];
 }
});
ready
medium array: forEach2 + native for-loop
arr2.forEach2(function(v, i, a, k) {
 for (i in k) {
  v = a[i];
 }
});
ready
big array: forEach2 + native for-loop
arr3.forEach2(function(v, i, a, k) {
 for (i in k) {
  v = a[i];
 }
});
ready
Opt small array
var i= arr.length, v;
while(--i){
 v = arr[i];
}
ready

Revisions

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