Exceptions: Exceptionally Slow
For almost everything you do, there’s always more than one way to skin a cat crack an egg, and coding is no exception. Ask 1000 programmers to write the same program and they will write it 1000 different ways. Sometimes this can get you in trouble and oftentimes experienced coders will see pitfalls before they make it into the code. Here’s a lesson learned we found that might help you in the future.
We were doing some math parsing with simple add/subtract/divide/multiply. Everything is very straightforward except for that pesky divide. Since you can’t divide by 0, we wrote unit tests to check for that case and coded to fix the tests.
Our first attempt had code that simply caught the DivideByZeroException and returned “0” for the result. It looked something like this:
It worked just fine and unit tests were happy.
Unfortunately, we ran into a strange bug that led one of our users to call and tell us that the system was being unusually slow. A quick check of the logs showed that we were attempting to divide by zero. But that couldn’t be the performance culprit, could it?
It turns out that exception handling is expensive…like My Super Sweet 16 expensive. See for yourself with this codeproject program. The single exception isn’t particularly slow, but we were calling this thousands of times and expecting it to only take a couple seconds. Using Visual Studio’s Performance Analysis should reveal this.
The fix was to check for that condition first with a simple if statement. If statements are one of the most common and fastest operations. Our performance on that call increased by a factor of nearly 1000x! Here’s what the code ended up looking like (it wasn’t this trivial of an example of course):
This is an example of the Tester-Doer method to deal with Exception performance. Microsoft recommends it on MSDN. For us, it worked very well. There are other techniques as well. Hopefully you can find one that works for you.
So if there’s anything you can learn from this, it’s that using exceptions to manage control flow is bad practice and should be avoided. They will cause you more trouble than they’re worth.