Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ return value versus exception performance

Somewhere I have read that modern Intel processors have low-level hardware for implementing exceptions and most compilers take advantage of it, to the effect that exceptions become faster than returning results state using variables.

Is it true? are exceptions faster than variables as far as returning state/responding to state? reading stack overflow on the topic seems to contradict that.

Thank you

like image 985
Anycorn Avatar asked Jul 04 '10 05:07

Anycorn


People also ask

Which is better a return code or an exception?

An application that uses exceptions is more robust than an application that uses return codes. An application that uses exceptions can also give the cleanest code, since return codes don't have to be checked after every call.

Why is throwing an exception better than returning an error value?

Return codes are more brittle The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception. The error won't be ignored.

Are exceptions inefficient?

"exceptions is always slow compared to other basic operations in the language, regardless of the programming language"... except in languages designed to compile use of exceptions into ordinary flow control.

Is exception handling cheap and efficient?

As a rule of thumb, exception handling is extremely cheap when you don't throw an exception. It costs nothing on some implementations. All the cost is incurred when you throw an exception: that is, “normal code” is faster than code using error-return codes and tests. You incur cost only when you have an error.


1 Answers

Be aware that there's ambiguity in the term "exception handler." I believe you'll find that hardware folks when talking about exceptions mean things like:

  1. Hardware interrupts, aka signals, whose handlers are sometimes called exception handlers (see http://pages.cs.wisc.edu/~smoler/x86text/lect.notes/interrupts.html)
  2. Machine check exceptions, which halt the computer if something in hardware goes wrong (see http://en.wikipedia.org/wiki/Machine_Check_Exception)

Neither of those has anything to do with C++'s exception handling facility.

As a counterexample, I have at least one anecdotal data point where exceptions were way slower than return codes: that was on Intel hardware alright, but with gcc 2.95 and a very large set of code with a very large exception table, that was constructed the first time an exception was thrown. Subsequent exceptions were fast, but by then the damage was usually done. Admittedly, gcc 2.95 is pretty ancient, but it should be enough to caution you about making generalizations about the speed of C++ exception handling, even on Intel hardware.

like image 81
Owen S. Avatar answered Sep 24 '22 06:09

Owen S.