Loop unrolling in JavaScript
August 16th, 2010One of the historically more popular optimizations is loop unrolling. Instead of a for
or while
loop, just “unroll” the loop:
// classic for loop for (var i = 0; i < 100; i++) a++; // unrolled loop a++; a++; a++; a++; a++; a++; a++; a++; // etc. etc. etc. // unrolled loop (in 1 statement) a++, a++, a++, a++, a++, a++, a++, /* ...etc... */ a++;
Try the test on jsPerf yourself.
Note that due to the lack of a goto
statement, loop unrolling has a bit of a limited appeal in JavaScript, but it’s still a useful technique in some cases, though you can use return
to return early from an unrolled loop (if the overhead of a function call is not too much).
…and here are results of the Austrian jury (on a 3.06GHz Core Duo):
Safari 5 (Mac): 3,228,374 ops/sec for the unrolled loop (22% faster than for loop)
Chrome 5 (Mac): 2,688,656 ops/sec for the unrolled loop (31% faster than for loop)
Firefox 3.6 (Mac): 42,890 ops/sec for the unrolled loop (for loop is 30x faster!)
IE 6 (XP): 60,235 ops/sec for the unrolled loop (1 statement version) (5x faster than for loop)
IE 8 (Win 7): 124,878 ops/sec for the unrolled loop (1 statement version) (5x faster than for loop)
The verdict is, that on modern JavaScript engines, unrolled loops give you a modest performance increase, and on Internet Explorer you can expect a major boost. On Firefox, normal for or while loops are better.
Mind you, NEVER OPTIMIZE PREMATURELY. Only optimize if you have to—but if so, this technique is actually quite useful, especially if you deal with iterative algorithms like in visualizations (something I sometimes have to deal with).
Find this technique and more in JavaScript Performance Rocks!, my ebook on JavaScript Peformance.
Tweet