2 ms·
Yeah, it's definitely not "zero cost" - I'm one of those people who are often heard saying things like "not-taken branches are almost zero cost", and perhaps I
by BeeOnRope 8y ago
Yeah, it's definitely not "zero cost" - I'm one of those people who are often heard saying things like "not-taken branches are almost zero cost", and perhaps I sometimes say the "almost" part under my breath.
First, setting the carry flag definitely has a cost. The function will either succeed or fail, and the compiler will have to set the carry flag appropriately. It will be fairly rare that the compiler can simply organize to have the carry flag set correctly without adding an additional instruction: for example on x86 I expect you'd see a clc instruction before most successful function returns.
I suppose where the error condition is checked within the function right before return, and the check uses the carry flag, and the carry flag happens to have the right polarity for success/failure, the compiler could optimize it out - but that doesn't seem common!
However, a nice advantage of using the carry flag is that "checking" it is simply a jump instruction, no test or cmp needed. On x86 this is less relevant due to macro-fusion often making the test basically free at runtime, but still nice.
A disadvantage would be any cases where the error check doesn't happen immediately after function return: if there is any other logic between the function call and the error condition check the compiler will probably have to stash the flag somewhere since it is clobbered by most instructions (at least on x86). The structured way the error handling is proposed to work probably makes that a non-issue in most cases, however.