Unlike some of the instructions below, the length of the array is not calculated at each iteration. Array length is a property that is set by modifying operations such as pop , push , shift , unshift , splice , etc.
You will see a slight increase in performance because, since property searches have a higher cost than a local variable . Therefore, caching lengths is a good idea. However, you will not see much difference if you are not dealing with huge data sets.
There is a special case where the length is actually calculated at each iteration. This happens with HTML node collections. Since these are living objects, length is not a property in the sense that it is with an array. If you do this:
for (var i=0; i < collection.length; i++) { collection[i] };
Then the collection is analyzed at each iteration.
As for optimizing the for loop, I usually use these methods for caching:
// if order is of no concern, just iterate from length-1 to 0 for (var i = arr.length - 1; i >= 0; i--){ arr[i] }; // use the for loop statement to set up scoped variables for (var i=0, length = arr.length; i < length; i++) { // do something }
source share