So i have known for a while that
for ( var i=0, len = myArray.length; i < len; i++ ){
}
is more efficient than
for ( var i=0; myArray.length; i++ ){
}
for large arrays. But have wondered how much of a performance gain does the former really give you ?
Today i set out to do some benchmarks. I created an array and pushed 100,000 numbers into it.
var array = [];
for( var i = 0; i < 100000; i++ )
array.push(i);
I then tested both loops above by doing a console.log of each of the numbers in the array and timing the process.
console.time('loop');
for( var i = 0; i < array.length; i++ )
console.log(i);
console.timeEnd('loop');
And for the second test
console.time('loop');
for( var i = 0, len = array.length; i < len ;i++ )
console.log(i)
console.timeEnd('loop')
After testing this a few times, my results are inconclusive. I get both high and low numbers for both test cases. So my question is, what's a better test to show unequivocally that getting the length beforehand has performance benefits and what kind of percentage gain is there to doing this ?
Here is a relevant jsperf: http://jsperf.com/caching-array-length/4 which shows that the difference can be surprisingly little.