Caching array's length (v7)

Revision 7 of this benchmark created on


Description

Should I cache the length of the array or can I access it every time in the loop?

Setup

var myArray = [];
    
    var length = 50000;
    
    for (var i = 0; i < length; i++) {
      myArray.push(Math.random());
    }

Test runner

Ready to run.

Testing in
TestOps/sec
With length
var total = 0;

for( var i = 0; i < myArray.length; i++ ) {
  total += myArray[ i ];
}
ready
cached length
var total = 0;

for( var i = 0, len = myArray.length; i < len; i++ ) {
  total += myArray[ i ];
}
ready
var outside loop
var total = 0
    , i
    , len = myArray.length
;

for( i = 0; i < len; i++ ) {
  total += myArray[ i ];
}
ready
var outside loop, =+ inc
var total = 0
    , i
    , len = myArray.length
;

for( i = 0; i < len; i+= 1 ) {
  total += myArray[ i ];
}
ready

Revisions

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