for vs array-foreach

JavaScript performance comparison

Revision 17 of this test case created

Preparation code

<script>

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

var array = Array(1000).join('xxxxxxxx').split('');
var callback = function(value, index, object) {
  return value;
};

var forEachIntern2 = function(_name, _array){
  this.name = _name;
  this.array = _array;
  this.callback = function(value, index, object) {
    return value;
  };
  this.each = function(){
    var i, arr = this.array, len = arr.length;
    for(i=0; i<len; i++) this.callback(arr[i], i, arr);
  };
};

var forEach = new forEachIntern2('forEachIntern2', array);

</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…
Internal Class
forEach.each();
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