The ramblings of web developer Beau Brownlee

 
May 14th, 2008

I’ve recently been working on a large javascript based application that does a lot of DOM manipulation. There are literally thousands of loops throughout the application that traverse the DOM and make changes in some way shape or form. The application has been running slow of late and we’ve been working through small ways to optimize performance. One of the things that I noticed is that literally all of our loops were written the following way:

for (var i=0; i<elements.length;>
{
//do something
}
</elements.length;>

I’ve known for awhile that it is more efficient to write your loops using a variable to hold the length instead of testing the array or array of elements with the .length function:

var l = elements.length;
 
for (var i=0; i<l;>
{
//do something
}
</l;>

I was curious, however, to know just HOW much the affected performance so I wrote a little test to benchmark the performance difference. In short when the page loads it appends 10,000 blank div tags to the body and the first button runs a script which runs the inefficient loop that traverses through all 10,000 divs and the second button uses the efficient looping method to traverse the DOM. The results actually surprised me. Here are the results that I got (results will obviously vary from machine to machine).

IE7 Firefox2 Firefox3 Opera Safari
Non-efficient loop 30,953 ms 484 ms 198 ms 79 ms 47 ms
Efficient loop 195 ms 344 ms 155 ms 79 ms 47 ms

As you can see IE was taxed the most by the inefficient code. You can imagine that with an application with thousands of loops all written this way how much this would slow down any javascript application. All other browsers seem to compensate for this code, safari being the most impressive.

Tags: ,

Related Links

One Response to “Javascript loop performance”

  1. David P Shenba Says:

    Great information. Thankyou

Leave a Reply

You must be logged in to post a comment.


cheap software