Exception-Terminated Loops Loops and Switches

- 153 -

7.2 Exception-Terminated Loops

This is a technique for squeezing out the very last driblet of performance from loops. With this technique, instead of testing on each loop iteration to see whether the loop has reached its normal termination point, you use an exception generated at the end of the loop to halt the loop, thus avoiding the extra test on each run through the loop. I include this technique here mainly because it is a known performance-tuning technique, but I do not recommend using it, as I feel it is bad programming practice the phrase enough rope to hang yourself springs to mind. Ill illustrate the technique with some straightforward examples. The full class for testing the examples is listed later, after I discuss the test results. The tests themselves are very simple. Basically, each test runs two varieties of loops. The first variety runs a standard for loop as you normally write it: for int loopvar = 0; loopvar someMax; loopvar++ The second variety misses out the termination test in the for loop, thus making the loop infinite. But these latter loops are put inside a try-catch block to catch an exception that terminates the loop: try { for int loopvar = 0; ; loopvar++ ... exception is thrown when loop needs to terminate } catchException e {} The three tests I use are: • A loop that executes integer divisions. The unterminated variety throws an ArithmeticException when a division by zero occurs to terminate the loop. • A loop that initializes an array of integers. The unterminated variety throws an ArrayIndexOutOfBoundsException when the index of the array grows too large. • A loop that enumerates a Vector . The unterminated variety throws a NoSuchElementException when there are no more elements to enumerate. I found the results of my test runs summarized in Table 7-1 to be variable due to variations in memory allocation, disk paging, and garbage collection. The VMs using HotSpot technology could show quite variable behavior. The plain JDK 1.2 VM had a huge amount of trouble reclaiming memory for the later tests, even when I put in pauses and ran explicit garbage-collection calls more than once. For each set of tests, I tried to increase the number of loop iterations until the timings were over one second. For the memory-based tests, it was not always possible to achieve times of over a second: paging or out-of-memory errors were encountered. Table 7-1, Speedup Using Exception-Driven Loop Termination Speedups 1.2

1.2 no JIT 1.3