JavaScript Simple Loop Optimisation

18th February 2008 - 3 minutes read time

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

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

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.

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

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.

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

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.

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

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.