Array.forEach vs. for-loop --> scaling

JavaScript performance comparison

Test case created by Kyle Simpson

Info

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 code

<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

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
small array: native forEach
arr.forEach(function(v, i, a) {
 v;
});
pending…
medium array: native forEach
arr2.forEach(function(v, i, a) {
 v;
});
pending…
big array: native forEach
arr3.forEach(function(v, i, a) {
 v;
});
pending…
small array: native for-loop
for (var i = 0, len = arr.length, v; i < len; i++) {
 v = arr[i];
}
pending…
medium array: native for-loop
for (var i = 0, len = arr2.length, v; i < len; i++) {
 v = arr2[i];
}
pending…
big array: native for-loop
for (var i = 0, len = arr3.length, v; i < len; i++) {
 v = arr3[i];
}
pending…
small array: forEach2 + native for-loop
arr.forEach2(function(v, i, a, k) {
 for (i in k) {
  v = a[i];
 }
});
pending…
medium array: forEach2 + native for-loop
arr2.forEach2(function(v, i, a, k) {
 for (i in k) {
  v = a[i];
 }
});
pending…
big array: forEach2 + native for-loop
arr3.forEach2(function(v, i, a, k) {
 for (i in k) {
  v = a[i];
 }
});
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. Here’s a list of current revisions for this page:

0 comments

Add a comment