Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DivideByZeroException too slow

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?

like image 510
Eduardo Avatar asked Feb 02 '10 11:02

Eduardo


1 Answers

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.

like image 158
Jon Skeet Avatar answered Sep 22 '22 09:09

Jon Skeet