One of the historically more popular optimizations is loop unrolling. Instead of a
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
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)
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).