3 ms·
I feel like I'm missing something in the conclusion. The initial question is: if (debug) { log("..."); } > Is it ok to have if clauses that will basi
by lttlrck 5y ago
I feel like I'm missing something in the conclusion.
The initial question is:
if (debug) {
log("...");
}
> Is it ok to have if clauses that will basically never be run?
And the summary is:
> If it's never-taken, it's probably ok. I found no evidence that such branches incur any extra cost. But do avoid always-taken branches and function calls.
However, if debug is false in the initial example, the branch is always taken, it's jumping over the call to log. Such code incurs a penalty - correct?
https://www.godbolt.org/z/o1Yd7oWYa https://www.godbolt.org/z/o1Yd7oWYa
- Scaevolus 5y agoGiven appropriate likeliness annotations or profile-guided optimization, it's possible for the compiler to _invert_ the conditional and move the log statement to a "cold" section of code outside of the main flow, making it a never-taken branch.
- PaulDavisThe1st 5y agoNot that this at all answers your question, and I'm guessing you know this already, but for a language with a preprocessor, that should be something more like: #ifndef NDEBUG #define DEBUG(msg) if (debug) { log (msg); } #else #define DEBUG(msg) #endif this eliminates any question of branch cost from an NDEBUG ("production" or "optimized") build, and you don't have to wonder. Obviously there are more sophisticated methods too.