Optimizing Loops in JavaScript

Not all JavaScript loops are identical. Try the code below by pasting the HTML in this tip into a file and then opening the file in your browser. You should find that the Duffs method provides the best optmization, while the second best optimization involves instantiating length in a variable and locally validating with it in the loop.

The optimization works for all common browsers, such as FireFox, IE, etc.

JavaScript loop speed test

JavaScript loop speed test

Loops through 10000 div elements in different ways. The time required for each loop is presented below in milliseconds.

Loop: for (var i=0; i

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

for (var i=0, il=divs.length; i

for duffs method

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: