Hacker News new | ask | show | jobs
by tsimionescu 1273 days ago
While you are absolutely right that collecting stack traces is an extremely costly operation, it's not the only problem. For example, in C++, which doesn't collect any kind of stack trace, throwing an exception is still ~1 order of magnitude slower than returning a value through all the layers. Note that this cost only happens when the exception is thrown; exception-based code is otherwise slightly faster than `if ret < 0` style C code, as the check is entirely omitted.

There is some explanation as to why this happens in this SO response [0]. The gist is that the dynamic nature of exception handling means that the compiler needs to consult runtime type information to decide where to jump when the exception is thrown, which means trawling through some relatively lengthy data structures. Adding to the problem, these data structures are not normally used a lot, so they are very likely not to be cached - though this may change for a program that actually throws exceptions in a hot loop, and the difference may not be as stark.

[0] https://stackoverflow.com/questions/13835817/are-exceptions-...

1 comments

Ah, fair, I don't have a lot of experience with C++. My answer was based on Java, which from the benchmarks I've seen doesn't suffer from any performance hit when you use a static exception object with no stacktrace.