Hacker News new | ask | show | jobs
by forgot_old_user 1269 days ago
I'm a little disappointed that the author doesn't explain why throwing the exception is much slower.
2 comments

For Java see The Exceptional Performance of Lil' Exception from Aleksey Shipilëv, https://shipilev.net/blog/2014/exceptional-performance. As always, Shipilëv does a fantastic job at explaining inner details of the JVM and observed performance profile.

A few years ago, I got hit by the high cost of an hidden exception (used for flow control by the JDK) while using LocalDate#format to parse a valid date. It was fun to troubleshoot and fix OpenJDK https://unportant.info/using-exceptions-for-flow-control-is-...

I would be interested in reading similar articles for other languages.

Stack traces. The information required to build a stack trace is deliberately kept off the critical path so it doesn't impact performance during normal operation, but that means that building a stack trace requires going out and fetching the debug symbols and correlating them.

Without stack traces, exceptions are just a type of goto.

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-...

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.
What about dynamic languages? Are they always collecting the stack and keeping it into some exception object that the exception can grab the data from at any time? And if that's the case wouldn't it always be slow regardless of raising or not ?
A performant dynamic language won't bundle the debug symbols either, so my assumption would be that the performance of an exception would still be bad.