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). I’ll 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
}
catch(Exception 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. ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.