for vs array-foreach (v6)

Revision 6 of this benchmark created by ryun on


Setup

var array = Array(10000).join('x').split('');
    
    function callback(value, index, object) {
      return value + index;
    }
    
    function customForEach(array, callback, thisArg) {
      var len = array.length;
      for (var i = 0; i<len; i++) {
        callback.call(thisArg, array[i], i, array);
      }
    }
    Array.prototype.forEach1 = function(fn, scope) {
        for(var i = 0, len = this.length; i < len; ++i) {
                fn.call(scope, this[i], i, this);
        }
    }
    
    Array.prototype.forEach2 = function( callback, thisArg ) {
    
        var T, k;
    
        if ( this == null ) {
                throw new TypeError( "this is null or not defined" );
        }
    
        var O = Object(this);
    
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32
    
        if ( {}.toString.call(callback) !== "[object Function]" ) {
                throw new TypeError( callback + " is not a function" );
        }
    
        if ( typeof thisArg !== 'undefined' ) {
                T = thisArg;
        }
    
        k = 0;
    
        while( k < len ) {
    
                var kValue;
    
                if ( Object.prototype.hasOwnProperty.call(O, k) ) {
                        kValue = O[ k ];
    
                        callback.call( T, kValue, k, O );
                }
                k++;
        }
    };
    
    Array.prototype.forEach3 = function(callback, thisArg)
    {
        var fn = callback,
        index = -1,
        length = this.length;
    
        while (++index < length) {
                if (callback(this[index], index, this) === false) {
                        break;
                }
        }
        return this;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Custom /Function
customForEach(array, callback);
ready
Native
array.forEach(callback);
ready
Compatibility/Shim
array.forEach1(callback);
ready
ECMA-262/Shim
array.forEach2(callback);
ready
Custom/Prototype
array.forEach3(callback);
ready

Revisions

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