JavaScript loop performance

When developing JavaScript, performance is one of the vital things. Therefore, I thought I’d share the performance of loops with JavaScript, and give some advice.

Three different loop approaches

Loop 1

The most common way to write a loop, and without a doubt the first way people learn how to do it, is like this:

for (var i=0; i<items.length; i++) {
    // Magic

The downside of that approach, however, is that for each iteration in the loop, it needs to test the current item and check the length of array/collection you’re looping through. This is a given performance hit.

Loop 2

Moving on to an approach which has become where popular amongst well-known JavaScript developers, probably for its short and nice syntax:

for (var i=0; divs[i]; i++) {
    // Magic

Problem with this, though, is that for each iteration you need to do a look-up of the array to see if an object exists at the current index.

Loop 3

The way I use, is to check the length of the array/collection when the loop is instantiated, and then just compare the current iteration index to the length saved in a variable.

for (var i=0, il=divs.length; i<il; i++) {
    // Magic

Running a speed test

I’ve created a little JavaScript loop speed test to show the different results for each loop type and web browser. The test creates 10 000 div elements when the page is loaded, and then runs the test when you click the “Start test” button.

The results are as follows:

Web browser Loop 1 Loop 2 Loop 3
IE 6 1141 109 0
IE 7 1032 31 0
Firefox 45 149 1
Safari 3.1 2 12 1
Opera 9.27 9 10 4

I think these results really show that it is important to think about how you write your loops. Sure, 10 000 elements doesn’t match most real scenarios, but still, with richer and richer pages, lots of queries run with a number of loops, it will add up.

What’s interesting to note here is that my recommended approach, loop 3, is considerably faster in all web browsers. And it’s even more fascinating to see that the current popular approach, loop 2, is the slowest in all web browsers but Internet Explorer.

Therefore, I’d like to recommend you to look over your loops, and consider loop 3 as your new way to code loops in JavaScript.

Posted in Developing,JavaScript,Technology,Web browsers |

Leave a Reply

Your email address will not be published. Required fields are marked *