for vs array-foreach (v17)

Revision 17 of this benchmark created on


Preparation HTML

<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

Ready to run.

Testing in
TestOps/sec
for-loop
for (var index = 0, length = array.length; index < length; index++) {
  callback(array[index], index, array);
}
ready
Array#forEach
array.forEach(callback);
ready
for-loop naive
for (var index = 0; index < array.length; index++) {
  callback(array[index], index, array);
}
ready
for-loop reversed
for (var index = array.length; index--;) {
  callback(array[index], index, array);
}
ready
for-loop (optimized)
var i; len = array.length;
for(i=0; i<len; i++) callback(array[i], i, array);
ready
Prototype Internal
array.forEachIntern();
ready
Internal Class
forEach.each();
ready

Revisions

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