for vs array-foreach

JavaScript performance comparison

Revision 6 of this test case created by ryun

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    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;
    }
};
</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
Custom /Function
customForEach(array, callback);
pending…
Native
array.forEach(callback);
pending…
Compatibility/Shim
array.forEach1(callback);
pending…
ECMA-262/Shim
array.forEach2(callback);
pending…
Custom/Prototype
array.forEach3(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