2

Exception handling incurs an overhead cost (as I understand).... and I appreciate IF statements/branching can cause slower code. However, assuming your program runs correctly for 99.9% of the time, the branch predictor would guess correctly most of the time and you wouldnt need exception handling overhead throughout the program...

Therefore, in performance-critical applications is it better to use IF statements rather than traditional exception handling for detecting errors?

user997112
  • 29,025
  • 43
  • 182
  • 361
  • 1
    See [How much footprint does C++ exception handling add](http://stackoverflow.com/questions/691168/how-much-footprint-does-c-exception-handling-add), there is no overhead when no exceptions occur whereas there is one with `if`-statements. – ipc Mar 22 '13 at 22:57
  • @ipc but I understood for exception handling to be enabled the run-time system has to keep track of more information IN CASE there is an exception...? This is why there is an option to compile without exception handling capabilities? – user997112 Mar 22 '13 at 22:58
  • Yes, but `assuming your program runs correctly for 99.9%`, this is not an issue. Exceptions should be used rarely anyway. – ipc Mar 22 '13 at 22:59
  • @user997112 There is only a slight penalty in binary size that shouldn't be important to most people. – Joseph Mansfield Mar 22 '13 at 23:04
  • 1
    Even in performance-critical applications, you should not bother about that unless your profiler tells you so (even if your platform is 200 MHz / 32 Mb RAM for a whole Linux -- which incidentally is what I happen to use). Premature optimization (micro- or otherwise) is the root of all evil. – syam Mar 22 '13 at 23:10

1 Answers1

6

A typical implementation of exception handling will add no more overhead (in terms of speed) to the main stream of execution than if statements will (and may even add a bit less). With reasonably careful use, it also reduces code clutter, enhancing readability.

IOW, for code where it makes sense at all, it's usually a fairly substantial win with very little downside. The main potential downsides are larger executables, and requirement for run-time support so it's not really suitable for things like device drivers (at least normally).

Brian Neal
  • 31,821
  • 7
  • 55
  • 59
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111