views:

110

answers:

3

Exception handling on Windows boxes (at least for C++) takes a performance hit if you exit a try block prematurely (such as executing a return statement) the same as if an exception were thrown.

But what about C#? Is there a performance hit for returning prematuraly from a try block, whether through a return statement or break statement?

A: 

All exception handling incurs a small performance overhead - there is always additional work that has to be done for any try/catch in existence.

THe question is not whether it is there, but whether it is RELEVANT. If I need to catch an exception, i need to. No dispute about performance.

TomTom
That doesn't answer his question.
T.J. Crowder
+7  A: 

If there is a performance hit, it's tiny. It's certainly nothing like the same as catching the exception. (And even that's not as bad as many people think.)

As far as I'm aware, the performance of returning from a try block is negligible. The chance of it being significant in your app is essentially 0. Just write the most readable code you can, and then benchmark/profile your app - that will be a much better way to get good performance than trying to second guess this sort of thing.

Jon Skeet
+1 *"the performance of returning from a try block is negligible"* And I can't imagine it's any different *at all* if you issue a `return` vs. just dropping out of the block.
T.J. Crowder
+1 "Premature optimization is the root of all evil" Donald Knut
bartek
Entering an actual try block itself is much costlier. I can't really imagine there is any difference between returning inside a try or returning after the try.
Steven
Would this still count if the exception was wrapped in a "finally" as this is similar to catching a thrown exception?
Mongus Pong
+3  A: 

No, there is no penalty what so ever for exiting prematurely from a try block.

I timed the difference between calling a method that returns in the middle of a try block and one that exits naturally out of the try block before returning, and there is no measurable difference.

There is a slight overhead for having the try block (about 0.000002 ms.), but no extra overhead for exiting in the middle of it.

Guffa