I'd like a response from someone who actually does real-time programming in C# or who really understands the language internals.
I know that exceptions should not be used to handle normal processing, but only to detect error conditions. There is plenty of discussion on that topic.
I'd like to know if there is any run time slow-down from simply having a try/catch block in place (which never catches an exception unless the program will have to end anyway). The try/catch block is inside a function which must be called repeatedly. I suspect there is only minimal cost.
Can the cost be quantified in terms of CPU cycles, or other tasks (same cost as a floating point multiplication), or another way?
We use Microsoft C#.Net 3.5 under windows XP.
.NET exceptions have a very, very low overhead cost unless they are thrown. Having a try/catch block in place will have a very minimal performance impact. I have found nearly no impact, even in very fast, tight loops, to having exception handling in place.
However, exceptions in .NET are VERY expensive when they're thrown. They tend to be much high-impact on performance if you throw them than many other languages. This is due to the full stack information gleaned when the exception is created, etc.
This is the opposite behavior to some other languages, such as python, where exception handling has a higher cost, but throwing is actually fairly performant.
However, if you are concerned, I would suggest you profile your routine, and test it yourself. This has been my experience after quite a bit of performance profiling. There is no substitution for measuring in your own codebase.
Good discussion, with metrics, of performance implications of try catch here.
Do try/catch blocks hurt performance when exceptions are not thrown?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With