for vs array-foreach

JavaScript performance comparison

Revision 16 of this test case created

Preparation code

<script>
Array.prototype.forEachFn = function(value, index, object) {
  //return value;
};
Array.prototype.forEachIntern = function() {
  var _this = this;
  var i; len = _this.length;
  for(i=0; i<len; i++) _this.forEachFn(_this[i], i, _this);
};

forEachIntern2 = function(array){
  var i; len = array.length;
  for(i=0; i<len; i++) callback(array[i], i, array);
};

forEachIntern3 = function(array, fn){
  var i; len = array.length;
  for(i=0; i<len; i++) fn(array[i], i, array);
};

var array = Array(1000).join('xxxxxxxx').split('');

var callback = function(value, index, object) {
  return value;
};

</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
for-loop
for (var index = 0, length = array.length; index < length; index++) {
  callback(array[index], index, array);
}
pending…
Array#forEach
array.forEach(callback);
pending…
for-loop naive
for (var index = 0; index < array.length; index++) {
  callback(array[index], index, array);
}
pending…
for-loop reversed
for (var index = array.length; index--;) {
  callback(array[index], index, array);
}
pending…
for-loop (optimized)
var i; len = array.length;
for(i=0; i<len; i++) callback(array[i], i, array);
pending…
Prototype Internal
array.forEachIntern();
pending…
forEachIntern2(array);
pending…
forEachIntern3(array, callback);
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