JavaScript Simple Loop Optimisation

When writing JavaScript applications I normally write for loops like this.

for (var i = 0; i < elements.length; ++i) {
  // loop...
}

There isn't anything wrong with this, but it is not an efficient way of doing things. All it takes is a little knowledge of what the for loop does every time it runs. The loop can be split into three sections like this.

for (/*initialise loop*/; /*test loop parameter*/; /*run command every loop*/) {
  // loop...
}

The first section initialises the loop, this allows you to set up counters that will be used for the duration of the loop and beyond. The second section is used to test for certain conditions at the start of each iteration of the loop, if the result is true then the loop continues, if it is false it stops. The third section is also run at the start of each iteration of the loop and is used to carry out a small calculation, like the incrementing of the loop counter. The third parameter isn't actually required and you could get by doing something like this.

for(var i = 0; i < elements.length;){
  ++i;
  // loop...
}

An excellent way of speeding up any loop is by setting up more than one variable within the initialisation section of the loop. If you are counting through the items in an array you will have to find out the length of the array every time you run through the loop. A more efficient way is to find out what the length of the array is at the start, store this value in a variable and then test the variable. Here is an example.

for (var i = 0,j = items.length; i < j; ++i) {
  // loop...
}

Here the length of the items array is stored as the variable j, which is then used to test against the loop counter i. This means you only need to find the length of an array once, not every time you run through the loop.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.