开发者

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜