4 ms·
Avoid exception throwing in performance-sensitive code
- trinovantes 4y agoOkay but why would you write code like that? You use exceptions when you have unhandled cases and may like a stack trace of how you ended up in such a state. It's like saying avoid using jumps instead of loops if you want readable code.
- Someone 4y agoI think the real rule is “in performance-sensitive code, pick the faster alternative” I don’t see it happen in this simple example with any language, but sometimes the occasional try/catch may be more readable/maintainable and fast enough for the goal. Also, sometimes all you have is the throwing version. Java’s Double.parseDouble is an example (https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)); https://docs.oracle.com/javase/7/docs/api/java/lang/Double.h... compare with C#’s Double.tryParse (https://docs.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-6.0 https://docs.microsoft.com/en-us/dotnet/api/system.double.tr...) which almost always is the better choice over Double.Parse (https://docs.microsoft.com/en-us/dotnet/api/system.double.parse?view=net-6.0 https://docs.microsoft.com/en-us/dotnet/api/system.double.pa...) If you need the speed, you could write your own non-throwing version, but I think that’s a last resort thing.
- mc4ndr3 4y agoAvoid exception throwing in most code. It's not a good error handling mechanism. Adjust the function signature so that the data types reflect the opportunity for a failed operation or failed input state. For example, Either monad (most languages). Or you can build one manually with a struct (C) or tuple (Go).