Raymond Chen's take on so-called zero cost exceptions

Elronnd elronnd at elronnd.net
Tue Mar 1 05:06:22 UTC 2022


On Tuesday, 1 March 2022 at 01:39:05 UTC, deadalnix wrote:
> obj can be kept in a register in the goto case, it cannot in 
> the exception case. So you'll have a couple extra load/store vs 
> extra branches.

Nope, it can be kept in a register in the exception case too.  
See: https://godbolt.org/z/zP1P3xvr3

The pushes and pops of RBX are necessary in both cases, because 
it is a caller-saved register.  (And, well, they are also 
necessary for stack alignment, so be wary of taking too many 
conclusions from a microbenchmark.)  Beyond that, note that the 
exception-using versions have fewer instructions in the hot path, 
fewer branches, and exactly the same number of memory accesses as 
the manually-checking versions.

(GCC generates better code, but clang's implementation of 'h' is 
more representative, which is why I show both; *usually* you 
can't run both the happy path and the sad path branchlessly.)


More information about the Digitalmars-d mailing list