As my research leads me to believe that for loops are the fastest iteration construct in javascript language. I was thinking that also declaring a conditional length value for the for loop would be faster... to make it clearer, which of the following do you think would be faster?
Example ONE
for(var i = 0; i < myLargeArray.length; i++ ) {
console.log(myLargeArray[i]);
}
Example TWO
var count = myLargeArray.length;
for(var i = 0; i < count; i++ ) {
console.log(myLargeArray[i]);
}
my logic follows that on each iteration in example one accessing the length of myLargeArray on each iteration is more computationally expensive then accessing a simple integer value as in example two?
I don't think you have anything to lose by going with the second version every time, although I would be surprised if the array length actually got calculated from scratch each time with the first approach unless the array actually gets mutated by the loop.
Don't forget that you can declare more than one variable in the first part of the
for
:Yes you are right myLargeArray.length is being calculate in each iteration of loop ( first example). link1 link2
Contrary to some of the statements below, the length of an Array is not calculated on each iteration. The length of an Array is a property which is set by modifying operations such as
pop
,push
,shift
,unshift
,splice
and so forth.You will see a minor performance hit though since a property lookup has a higher cost than a local variable. Therefore caching the length is a good idea. However you won't see a big difference unless you are dealing with huge datasets.
There is a special case though where the length is indeed calculated on each iteration. This is the case with HTML node collections. Since these are live objects, the length is not a property in the sense it is with an array. If you do this:
Then the collection is parsed on each iteration.
As for optimizing a for loop, I usually use these techniques for caching:
From JavaScript Garden, a great resource on the quirks of JavaScript.
From High Performance JavaScript
Decreasing the work per iteration:
Decreasing the number of iterations:
See JavaScript Optimization