46

This link states,

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

Does it mean that having a try block reduces performance due to the extra task of "inspection" during run time?

razlebe
  • 7,134
  • 6
  • 42
  • 57
bibbsey
  • 969
  • 2
  • 9
  • 14
  • Typically yes, but unless it's a time-critical, called-a-million-times, must-be-really-fast portion of code, I wouldn't base my decision of whether or not to use exceptions on this. – Luchian Grigore May 28 '13 at 05:41
  • (Note that the answer will depend upon what compiler you use, as opposed to Java/C#/Python where exception handling is only ever done in one way.) (However, a good try/catch exception has almost 0 or 0 overhead in the case where no exception is thrown.) – Patashu May 28 '13 at 05:41
  • This might answer your question: http://stackoverflow.com/questions/1897940/in-what-ways-do-c-exceptions-slow-down-code-when-there-are-no-exceptions-thown/1897979#1897979 – Jeremy Friesner May 28 '13 at 05:42
  • 4
    Compared to what? Handling the exceptional condition some other way (if so, how?) or simply not handling the exceptional condition and hoping it never happens. – CB Bailey May 28 '13 at 05:57
  • better dupe, IMO: https://stackoverflow.com/questions/13835817/are-exceptions-in-c-really-slow – underscore_d Oct 23 '17 at 11:20

5 Answers5

95

TL;DR NO, exceptions are usually faster on the non-exceptional path compared to error code handling.


Well, the obvious remark is compared to what ?

Compared to not handling the error, it obviously decrease performance; but is performance worth the lack of correctness ? I would argue it is not, so let us supposed that you meant compared to an error code checked with an if statement.

In this case, it depends. There are multiple mechanisms used to implement exceptions. Actually, they can be implemented with a mechanism so close to an if statement that they end up having the same cost (or slightly higher).

In C++ though, all major compilers (gcc introduced it in 4.x serie, MSVC uses it for 64 bits code) now use the Zero-Cost Exception Model. If you read this technical paper that Need4Sleep linked to, it is listed as the table-driven approach. The idea is that for each point of the program that may throw you register in a side-table some bits and pieces that will allow you to find the right catch clause. Honestly, it is a tad more complicated implementation-wise than the older strategies, however the Zero Cost name is derived by the fact that it is free should no exception be thrown. Contrast this to a branch misprediction on a CPU. On the other hand, when an exception is thrown, then the penalty is huge because the table is stored in a cold zone (so likely requires a round-trip to RAM or worse)... but exceptions are exceptional, right ?

To sum up, with modern C++ compilers exceptions are faster than error codes, at the cost of larger binaries (due to the static tables).


For the sake of exhaustiveness, there is a 3rd alternative: abortion. Instead of propagating an error via either status or exception, it is possible to abort the process instead. This is only suitable in a restricted number of situations, however it optimizes better than either alternative.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
7

Take a look at Section 5.4 of draft Technical Report on C++ Performance which is specifically about the overhead of try-catch statements in c++.

A little excerpt from the section:

5.4.1.1.2 Time Overhead of the “Code” Approach

• On entry to each try-block
    ♦ Commit changes to variables enclosing the try-block
    ♦ Stack the execution context 
    ♦ Stack the associated catch clauses 
• On exit from each try-block
    ♦ Remove the associated catch clauses 
    ♦ Remove the stacked execution context 
• When calling regular functions 
    ♦ If a function has an exception-specification, register it for checking 
• As local and temporary objects are created 
    ♦ Register each one with the current exception context as it is created 
• On throw or re-throw 
    ♦ Locate the corresponding catch clause (if any) – this involves some runtime check (possibly resembling RTTI checks) 
    If found, then: 
    destroy the registered local objects 
    check the exception-specifications of the functions called in-between 
    use the associated execution context of the catch clause 
    Otherwise: 
    call the terminate_handler6
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
  • 6
    Summarize, so that when the link inevitably becomes dead the answer is still useful. – Patashu May 28 '13 at 05:42
  • 1
    @Patashu open-std is a holding website, it's main goal is to preserve these links. – Syntactic Fructose May 28 '13 at 05:43
  • 4
    Even sites with good intentions can go down. SO policy is no link only answers. – Patashu May 28 '13 at 05:45
  • 6
    -1 The intention may be good, but the document specifically listed **2 approaches** (code-driven and table-driven), and you unfortunately listed the code-driven approach... which is only used by MSVC in 32 bits mode by now (among the major compilers). The table-driven approach, instead, is *faster* (than an `if` statement) and *fatter* (although the fat is isolated in a cold-code zone). I encourage you to read about it, its pet name is Zero-Cost Exception Model. – Matthieu M. May 28 '13 at 06:17
2

It depends. For exception handling, the compiler has to do something - otherwise it could not do stack unwinding and such. That means yes, exception handling decreases performance - even if the exception is not thrown. How much - this depends on your compilers implementation.

On the other hand you have to question yourself: If you insert your error handling code yourself, would it really be faster (measure it - don't guess it). Can it do the same as exceptions (exceptions can't be ignored by the client - error codes can - and they can do stackunwinding which error codes can't). Additionally, the code can be written to be more maintainable with exceptions.

Short: unless your code is very very very very very time critical, use exceptions. Even if you decide against them: measure first. One exception to the rule: it's a bad idea to throw exceptions across module boundaries or in a destructor.

Tobias Langner
  • 10,634
  • 6
  • 46
  • 76
2

It really depends on the specific compiler.

If the compiler prefers to consider exception throwing a really exceptional condition then you can implement a scheme where in case of no exception you have zero-overhead but that, in turn, will cost more time in case of an exception and/or more code size.

To implement a zero-overhead approach you can notice that in C++ you cannot dynamically change code so once you know what is the stack frame and the return address it's fixed what are the objects that must be destroyed in case of unwinding or if there is an exception handling code section. The code for throwing an exception could therefore check a global table of all function call sites to decide what should be done.

On the other side you can make exception throwing faster by preparing the list of objects to be explicitly destroyed and the address of the exception handling code during normal execution. This will make regular code slower, but exception handling faster and also I'd say code a bit smaller.

Unfortunately there is no standard way in C++ to completely give up exception support, so something has to be paid to this possibility: the standard library throws exceptions and any code that calls unknown code (e.g. using a function pointer or calling a virtual method) must be prepared to handle an exception.

6502
  • 112,025
  • 15
  • 165
  • 265
1

I would recommend adding try catch in functions which does memory allocation, deletion, calling another complex functions etc. Actually performance wise try catch adds a little bit of overhead.

But considering the merit of catching the unknown exceptions it is very helpful. Good programming practices always recommend adding some kind of exception handling in your code unless you are an exceptional programmer.

I wonder why you are so concerned about small performance issue than the entire program being stuck with an exception.

CodeRider
  • 1,750
  • 6
  • 18
  • 34