Reputation: 439
known that the generation of exceptions reduces the performance
but I could not find the reason for this
why the generation of exceptions reduces the performance?
Upvotes: 2
Views: 174
Reputation: 113262
Well, because it does something. Doing anything takes time.
Throwing an exception creates an object, obtains a copy of the stack, walks the stack up to two times, and perhaps marshals across domains. Doing stuff takes time. In an ideal world it will also be the branch that wasn't predicted as being taken (because it should be the branch that was less likely) though I've no idea if that's the case or not. It's also particularly likely to lead to cases where the caches are being refilled because control has moved to somewhere "far away".
All that said though, exceptions aren't particularly slow except when being run in a debugger (which for obvious reasons does more work again when an exception is thrown). It's slow enough that doing try-and-catch in a loop where doing test-and-try or tryparse-and-report makes more sense is a bad idea, but these fall into the category of good micro-optimisations ("micro-optimisation" is often used as a slur, but when the approach that's semantically clearer is also slightly more performant then it's a good thing for the reason of that clarity - it's when we make things less clear and semantically sensible for the sake of a few cycles that "micro-optimisation" becomes a negative).
Upvotes: 1
Reputation: 29243
"If you ever get to the point where exceptions are significantly hurting your performance, you have problems in terms of your use of exceptions beyond just the performance." - Jon Skeet
In other words, if you use them for what they were intended, that is exceptional cases and not regular control flow, the performance penalty of throwing exceptions should not be a problem.
Upvotes: 0
Reputation: 62504
One of the things which impact cost of an exception throw is a pretty informative Exception object with a call stack information. This cost some time and memory space to build and keep this neat information for us. For instance unmanaged C++ does not have such informative call stack so debugging in C++ more complex task.
Upvotes: 0