Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of "returning" from a Try block

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?

like image 376
Brent Arias Avatar asked May 12 '10 05:05

Brent Arias


People also ask

Can you return in a try block?

you can use a return statement inside the try block, but you have to place another return outside the try block as well. If you pass true while calling sayHello method, it would return from try block. A return statement has to be at the method level instead of at any other specific level.

Is it good practice to return from catch block Java?

You can return normally from catch block. It's normally good functional code.

Can we return from TRY block C#?

Yes, we can write a return statement of the method in catch and finally block.

Does the finally block get executed if either of try or catch blocks return the control?

Yes, the finally block will be executed even after a return statement in a method.


1 Answers

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.

like image 103
Jon Skeet Avatar answered Nov 12 '22 05:11

Jon Skeet