Using Exceptions throwing in C#. Does it affect a performance?

后端 未结 8 861
余生分开走
余生分开走 2021-01-13 01:58

Basically, the question is: Do the Exceptions in C# affect the performance a lot? Is it better to avoid Exceptions rethrow? If i generate an exception in my code, does it a

相关标签:
8条回答
  • 2021-01-13 02:27

    Microsoft's Design Guidelines for Developing Class Libraries is a very valuable resource. Here is a relevant article:

    Exceptions and Performance

    I would also recommend the Framework Design Guidelines book from Microsoft Press. It has a lot of the information from the Design Guidelines link, but it is annotated by people with MS, and Anders Hejlsberg, himself. It gives a lot of insight into the "why" and "how" of the way things are.

    0 讨论(0)
  • 2021-01-13 02:29

    Raising an exception is an expensive operation in C# (compared to other operations in C#) but not enough that I would avoid doing it.

    I agree with Jared, if your application is significantly slower because of raising and throwing exceptions, I would take a look at your overall strategy. Something can probably be refactored to make exception handling more efficient rather than dismissing the concept of raising exceptions in code.

    0 讨论(0)
  • 2021-01-13 02:32

    What most other folks said, plus: Don't use exceptions as part of the programming flow. In other words, don't throw an exception for something like, account.withdrawalAmount > account.balance. That is a business case.

    The other biggie to look out for regarding performance is swallowing exceptions. It's a slippery slope, and once you start allowing your app to swallow exceptions, you start doing it everywhere. Now you may be allowing your app to throw exceptions that you don't know about because you are swallowing them, your performance suffers and you don't know why.

    0 讨论(0)
  • 2021-01-13 02:34

    This is not silly just I've seen it somewhere else also on SO.

    The exceptions occur well, when things are really exceptional. Most of the time you re-throw the exception (may after logging) when there are not many chances of recovering from it. So it should not bother you for normal course of execution of program.

    0 讨论(0)
  • 2021-01-13 02:38

    Exceptions in .NET do affect performance. This is the reason why they should be used only in exceptional cases.

    0 讨论(0)
  • 2021-01-13 02:42

    If you're worried about exception performance, you're using them wrong.

    But yes, exceptions do affect performance.

    0 讨论(0)
提交回复
热议问题