Try Catch Overhead

BlitzMax Forums/BlitzMax Programming/Try Catch Overhead

BLaBZ(Posted 2012) [#1]
How does Try Catch work on a low level?

Is there much\any overhead with try catch?


Yasha(Posted 2012) [#2]
I was wondering about this but couldn't find the actual implementation details through poking around in what source is provided.

Based on certain comments made by the linker (when it hits errors) and the fact that the runtime is implemented in C (as opposed to C++), I would assume that it uses setjmp/longjmp to implement exceptions rather than modern C++-style zero-overhead exceptions, so general comments you can find online about the overhead of using SJLJ exceptions in C++ can probably be applied to BlitzMax as well (normally said to be a 10% slowdown).

Exceptions are likely more expensive in BlitzMax than in other high-level languages because of the reliance on reference counting as the GC implementation strategy: you can't just jump out of a function's scope and forget about it, you have to release any object references it has (and that its jumped-over callers have) as you discard the call chain. This means that "throw" actually has to "do stuff" beyond simply jumping to a different code location and will therefore be quite weighty (in a language with a tracing GC no cleanup is required so exceptions can be made very lightweight, e.g. OCaml where they're considered the preferred way to break out of loops, which is unusual).

The fact that every call frame must be dealt with in some way before it can be discarded is similar to the implementation issues created by C++'s RAII, so again the overhead is probably similar to a C++ SJLJ implementation.

Basically... use them where speed doesn't matter. Don't use them as a substitute for Exit. Don't use them to propagate soft error conditions (e.g. bad input) out of high-performance sections of your program: use return codes instead.

Also while exceptions make code much easier to write, they can make it harder to read since they're effectively an untargeted Goto. Some people really hate them for this reason. I don't, but do be nice to the people who have to read your code and work out where the control flow actually goes.