Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does try catch in C++ affect performance when not hit

Tags:

c++

try-catch

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?

like image 286
Man Kun Avatar asked Oct 30 '22 00:10

Man Kun


1 Answers

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

like image 70
mvidelgauz Avatar answered Nov 15 '22 04:11

mvidelgauz