Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Real Time Try Catch

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.

like image 218
Mark T Avatar asked Aug 28 '09 15:08

Mark T


2 Answers

.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.

like image 194
Reed Copsey Avatar answered Sep 21 '22 10:09

Reed Copsey


Good discussion, with metrics, of performance implications of try catch here.

Do try/catch blocks hurt performance when exceptions are not thrown?

like image 21
Gratzy Avatar answered Sep 23 '22 10:09

Gratzy