X is true nearly 99.9% of the time but I need to handle Y and Z as well. Although the body of the X condition is empty, I'm thinking it should be faster than potentially checking 2 other conditions Y and Z if the X condition is omitted. What do you think?
if (likely(X))
{
}
else if (unlikely(Y))
{
...
}
else if (unlikely(Z))
{
...
}
Efficient if-else Statements While in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.
The if statement is the most expensive [something]. [something] registers [something].
Nope. In fact, it'll actually speed it up in most cases (because it's allowed to skip over blocks of code). If you're considering merging a bunch of if statements into one: don't, you won't get any benefits.
You might want to know what exactly happens when you use likely or unlikely:
http://kerneltrap.org/node/4705
I would personally write
if (unlikely(!X))
{
if (unlikely(Y))
{
...
}
else if (unlikely(Z))
{
...
}
}
Which means if x
, continue execution, else jump to if body.
As usual, when in doubt profile; anyhow, if I were to read that code I would find much clearer something like:
if (!likely(X))
{
if (unlikely(Y))
{
...
}
else if (unlikely(Z))
{
...
}
}
If a compiler is to assume, it would generally favor the first condition true.
you can use something like __builtin_expect
to control this (as Ugo detailed).
If it's in a loop, you should measure because hardware is also a consideration -- it's not just the source and the compiler. How's your cache, and how's branch prediction working for you? Profile. Alter. Profile. Compare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With