Home > Javascript > Javascript “For” Loops and micro-optimizations

Javascript “For” Loops and micro-optimizations

Loops execute a block of code a specified number of times, or while a specified condition is true.

In JavaScript, there are two different kind of loops:

  • for: loops through a block of code a specified number of times
  • for-in: loops that should be used to iterate over non-array objects, an action also called enumeration
  • while: loops through a block of code while a specified condition is true

A typical for loop white you iterate over array-like objects or arrays looks like:

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = 0; i < myArray.length; i++){
    console.log(myArray[i]);
}

This will log the 10 numbers inside the myArray array. This is a way to iterate through myArray’s element but not the optimal.

The problem with the above loop is that the length property of the array is accessed on every iteration and this can slow down things especially while iterating through HTMLCollection objects.

One simple thing you can do is to cache the length property of the collection you are iterating over and to achieve this you can change the above code with the following:

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = 0, length = myArray.length; i < length; i++){
    console.log(myArray[i]);
}

This will have the same result as before but the value of length property will be calculated and retrieved only once during the whole iteration.

One last tweak could be to change the i++ to i+=1 as post-increment and post-decrement have been implicated in many of the worst buffer-overrun security errors. (JSLint also prompts you to do this specifying that ++ and – promote “excessive trickiness”)

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = 0, length = myArray.length; i < length; i+=1){
    console.log(myArray[i]);
}

Other micro-optimizations could be to write the for loop counting down to 0, as it’s faster and more efficient to compare to 0 than to the length of an array or anything else other than 0

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = myArray.length; i-=1){
    console.log(myArray[i]);
}

OR

var i = myArray.length;
while(i-=1){
    console.log(myArray[i]);
}
Categories: Javascript Tags: ,