Chapter 10: Optimizing JavaScript for Execution Speed

Table 10.2: Loops Optimizations Compared

The following tests demonstrate local loop optimizations compared to a for loop. Do while (flipped), reversed (counting down instead of up), do while reversed, pre- and post-decrement simplified conditionals can all speed up your loops and reduce loop overhead. The third Do While (flipped loop with optimized reverse count) is over four times faster than a normal for loop. Note that the pre-decrement operator conditional in the while loop assumes that i is greater than 0.

Normal Do While Reverse Do While Reverse Do While Reverse2 Do While Reverse3
Total: ms Total: ms Total: ms Total: ms Total: ms Total: ms
Per Cycle: ms Per Cycle: ms Per Cycle: ms Per Cycle: ms Per Cycle: ms Per Cycle: ms