Caching Array Length

JavaScript performance comparison

Revision 51 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var theArray = [ "", 56, function() {}, 93, "lalala", {} ];
    for( var i = 0; i < 200; i++ )
      theArray.push( theArray[i] );
    var copyOfTheArray = new Array( theArray.length ); // []
   
};
</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
With length caching
var len = theArray.length;
for (var i = 0; i < len; i++) {
  copyOfTheArray[i] = theArray[i];
}
pending…
Without length caching
for( var i = 0; i < theArray.length; i++ )
  copyOfTheArray[i] = theArray[i];
 
pending…
for push
copyOfTheArray = [];
for( var i = 0; i < theArray.length; i++ )
  copyOfTheArray.push( theArray[i] );
 
pending…
for-in push
copyOfTheArray = [];
for( var x in theArray )
  copyOfTheArray.push( theArray[x] );
 
pending…
forEach()
theArray.forEach( function( value, i ) {
  copyOfTheArray[ i ] = value;
} );
 
pending…
while backwards
var len = theArray.length;
while( len-- )
  copyOfTheArray[ len ] = theArray[ len ];
 
pending…
loop cached function
( function arrayForEach( array, action ) {
  for( var i = 0, j = array.length; i < j; i++ )
    action( array[i], i );
} )( theArray, function( item, i ) {
  copyOfTheArray[i] = item;
} );
 
pending…
for-in
for( var i in theArray )
  copyOfTheArray[i] = theArray[i];
 
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