Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run-time penalty of C++ try blocks [duplicate]

Possible Duplicate:
Measuring exception handling overhead in C++
Performance when exceptions are not thrown (C++)

I have heard anecdotally that using "try" blocks in C++ slows down the code at run-time even if no exceptions occur. I have searched but have been unable to find any explanation or substantiation for this. Does anyone know if this is true & if so why?

like image 445
GigaQuantum Avatar asked Jan 10 '12 14:01

GigaQuantum


2 Answers

The answer, as usually, is "it depends".

It depends on how exception handling is implemented by your compiler.

If you're using MSVC and targeting 32-bit Windows, it uses a stack-based mechanism, which requires some setup code every time you enter a try block, so yes, that means you incur a penalty any time you enter such a block, even if no exception is thrown.

Practically every other platform (other compilers, as well as MSVC targeting 64-bit Windows) use a table-based approach where some static tables are generated at compile-time, and when an exception is thrown, a simple table lookup is performed, and no setup code has to be injected into the try blocks.

like image 77
jalf Avatar answered Oct 06 '22 20:10

jalf


There are two common ways of implementing exceptions.

One, sometimes refered to as "table-based" or "DWARF", uses static data to specify how to unwind the stack from any given point; this has no runtime overhead except when an exception is thrown.

The other, sometime referred to as "stack-based", "setjmp-longjmp" or "sjlj", maintains dynamic data to specify how to unwind the current call stack. This has some runtime overhead whenever you enter or leave a try block, and whenever you create or destroy an automatic object with a non-trivial destructor.

The first is more common in modern compilers (certainly GCC has done this by default for many years); you'll have to check your compiler documentation to see which it uses, and whether it's configurable.

like image 38
Mike Seymour Avatar answered Oct 06 '22 19:10

Mike Seymour