views:

99

answers:

5

It would appear that catching an error is slower that performing a check prior to the error (for example a TryParse). The related questions that prompt this observation are here and here.

Can anyone tell me why this is so - why is it more costly to catch an error that to perform one or many checks of the data to prevent the error?

+5  A: 

Basically, it's the unwinding of the stack that's most expensive. Here's a great link: http://stackoverflow.com/questions/164613/why-are-try-blocks-expensive

dcp
A: 

A quick answer is "because of the context switching and the stack walking required to find the root of the exception."

AlfredBr
A: 

I think that it's generally to do with building up the exception object, it has to do a number of things, such as unwinding the call stack, which are relatively costly.

Paddy
+3  A: 

Throwing an exception is costly. The reasons are numerous, but its mostly due to the need to build the stack trace and cleanly exit the nested scope(s) until you find the appropriate catch statement.

Actual performance will depend on the characteristics of your app. Take the following two blocks of code:

A:

if (foo.CanFizz)
    foo.Fizz();

B:

try { foo.Fizz(); }
catch (NotFizzableException) { /* etc. */ }

Conventional wisdom would say that the first is faster, but if you expect foo.CanFizz to be true most of the time, then the second may actually perform better. The cost of checking the guard condition every time may be higher than the cost of catching the exception in the unusual case that the guard condition is false.

Of course, premature optimization is the root of all evil. Don't even bother to think about this until you know that this is a performance bottleneck.

JSBangs
A: 

The performance hit isn't from "errors" in general, it is from exceptions, and specifically the various things that must be done when an exception is thrown (creation of exception object, stack unwinding, context switching).

Remember though: exceptions are for exceptional behaviour

It shouldn't matter that throwing/catching an exception is "slow" (and it really isn't that slow) because if you are into exception handling code then you should be outside the expected normal flow of your program.

GrahamS