Reputation: 51
I have code where there is a try catch in a function and the function gets hit. 100+ times. The code return early everytime without actually hitting the try catch. Does this affect performance in Visual Studio. I am seeing a performance impact.
My code was :
void foo(int a) {
if (a > value) {
return;
}
try {
possibleErrorFunction();
} catch {
}
}
I changed it to:
void foo(int a) {
if (a > value) {
return;
}
bar();
}
void bar() {
try {
possibleErrorFunction();
} catch {
}
}
The second code seems about 10 sec faster. Is there any resaonable explanation for this?
Upvotes: 5
Views: 3201
Reputation: 71
In my opinion the reason of the observable difference in performance may be the fact that methods/functions containting try/catch block will not be inlined, at least for sure not by MSVC compiler (see https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4714?view=msvc-170 )
Before the change void foo(int a) couldn't be inlined. After the change it may have been inlined.
Upvotes: 0
Reputation: 2214
There are 2 major policies used in exception mechanism implementation. One is so-called "frame based", or "dynamic" and another one is "table based". Other schemes are variations of those two. You can read more about them here
In essence, "frame-based" dynamic implementation does spend resources on each entry into and exit from try
block at run-time. The "table based" mechanism does not involve any extra work if exception is not thrown but it uses much more memory.
I am not 100% sure but as far as I know Microsoft compiler up till VS2008 used "frame-based" approach and starting from VS2010 it implements "table-based" approach. (Maybe there are some compiler switches that can control it - I don't know because I personally prefer not to use exceptions until forced by existing code or 3rd party libraries). I think you can find this information in your compiler documentation.
You could also produce assembler code from your c++ source to see what is going on with your try
block
Upvotes: 2
Reputation: 467
All of the above comments seem to converge toward a useful point or two. Extra apparatus always engages more CPU cycles and thus derogatively affects performance (I can't believe this editing box flagged "derogatively"). Many iterations over many instances are required.
Upvotes: 0