This is extremely slow:
try
{
x = k / y;
}
catch (DivideByZeroException) { }
This is about 5x faster:
if (y > 0) x = k / y;
Can anybody tell me why?
Only 5 times faster? You do surprise me. Presumably that means your sample data doesn't have many zeroes in it.
Exceptions are more expensive than simple comparisons. When used correctly (i.e. for exceptional circumstances) they don't tend to hamper performance significantly - because if you're throwing enough exceptions for it to make a big impact, chances are your service is already hosed. It does cause a problem when you use exceptions to try to ignore conditions which you could very easily test to start with - like this one.
One thing to note about the cost of exceptions: they cost a lot more in the debugger than when running without a debugger attached; in particular the first exception which needs to load a bunch of resources can take seconds rather than micro/milliseconds. If you're going to benchmark code, it's vital that you don't do it in a debugger - that's true in general, but particularly for exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With