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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.