top | item 34089137

(no title)

forgot_old_user | 3 years ago

I'm a little disappointed that the author doesn't explain why throwing the exception is much slower.

discuss

order

unportant|3 years ago

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.

lolinder|3 years ago

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.

tsimionescu|3 years 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-...

aprdm|3 years ago

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 ?