Question

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 ?

Était-ce utile?

La solution

Here is a relevant jsperf: http://jsperf.com/caching-array-length/4 which shows that the difference can be surprisingly little.

Autres conseils

In this case, it doesn't make any difference. Accessing the length property of an array is a very quick operation since it is updated every time the array changes, and thus you're just retrieving a number.

If, however, you were looping through say some elements that you got through document.querySelectorAll, then it might be a good idea to cache the results, because the call to querySelectorAll can be expensive, and you don't want to run it every iteration if the results won't change.

Theoretically there shouldn't actually be any difference in speed between your two examples.

The idea that the first example will run faster come from languages like php where the equivalent would be "$i < sizeof($array)" since sizeof has the count the length of the array on every iteration of the loop. Unlike PHP though, JavaScript already knows how long its arrays are, so your pretty much just reading the number directly.

The result is that in JavaScripts case the only difference between reading "arrlen" and "somearray.length" is where the pointer is pointing, so the speed will be pretty much identical.

That said, by the looks of the benchmarks Joseph posted, how this is being handled under the hood is obviously not so straight forward. In the case of chrome 15 inline actually seems to be faster, while in the older few its a little bit slower? o.0

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top