Breaking out of a recursion in java

No matter what you do, you are going to have to unwind the stack. This leaves two options:

  1. Magic return value (as described by one of the Toms)
  2. Throw an exception (as mentioned by thaggie)

If the case where you want things to die is rare, this may be one of those situations where throwing an exception might be a viable choice. And before everyone jumps down my throat on this, remember that one of the most important rules of programming is knowing when it’s appropriate to break the rule.

As it turns out, I spent today evaluating the zxing library from google code. They actually use exception throws for a lot of control structures. My first impression when I saw it was horror. They were literally calling methods tens of thousands of times with different parameters until the method doesn’t throw an exception.

This certainly looked like a performance problem, so I made some adjustments to change things over to using a magic return value. And you know what? The code was 40% faster when running in a debugger. But when I switched to non-debugging, the code was less than 1% faster.

I’m still not crazy about the decision to use exceptions for flow control in this case (I mean, the exceptions get thrown all the time). But it’s certainly not worth my time to re-implement it given the almost immeasurable performance difference.

If your condition that triggers death of the iteration is not a fundamental part of the algorithm, using an exception may make your code a lot cleaner. For me, the point where I’d make this decision is if the entire recursion needs to be unwound, then I’d use an exception. IF only part of the recursion needs to be unwound, use a magic return value.

Leave a Comment