4 ms·
The part about “non trivial code” does a lot of lifting here. I would say your statement is untrue in general in at least a few languages. In .NET and Java it
by throw-qqqqq 2y ago
The part about “non trivial code” does a lot of lifting here. I would say your statement is untrue in general in at least a few languages.
In .NET and Java it costs at least 100x as much time to throw an exceptions as to return an error code.
Other languages may have cheaper exceptions, but for many mainstream languages, you pay a big performance price for exceptions.
That price is often offset by other positive things, so the tradeoff is made willingly and with eyes open.
- elygre 2y agoYou pay the cost only when the exception is raised. If that happens on more than 1% of your runtime checks, it probably is not (aka should not be) an exception.
- tempodox 2y agoYou wouldn't run .NET or Java on a spacecraft MCU and setjmp/longjmp in C are as cheap as it gets for exception handling.
- jayd16 2y ago> In .NET and Java it costs at least 100x as much time to throw an exceptions as to return an error code. The conjecture is that if checks are always executed while exceptions are free when not thrown. That said, predicted branches are also fairly free so arguing about this in the abstract is pointless.
- rocqua 2y agoIn the margin, branches are more likely close to the hot path, so they are more likely to 'pollute' the instruction cache. Whilst exceptions have less of this. Though profile guided optimization will probably catch this. And it might be that even without, compilers still optimize around this.
- mkleczek 2y ago> In .NET and Java it costs at least 100x as much time to throw an exceptions as to return an error code. Don't know about .NET but in Java it is not throwing exceptions that is heavy but filling in stack trace during construction of a Throwable. It can be made much more performant using constructor that disables stack trace: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Throwable.html#%3Cinit%3E(java.lang.String,java.lang.Throwable,boolean,boolean) https://docs.oracle.com/en/java/javase/21/docs/api/java.base...