I’ve a conditional statement expensive_foo() which is false in 99.9% cases. And I have a conditional statement bar which is true in ~50% cases.
And I want some action be done if both statements are true. So I almost certainly know that expensive_foo() is false and I want to check it only if bar is true.
Will the code below check the expensive_foo() ONLY if bar is true? Or it will check expensive_foo() every time?
if ( bar && expensive_foo() )
{
...
}
Or I need to make a structure like this:
if ( bar )
{
if ( expensive_foo() )
{
...
}
}
The logical AND operator
&&is short-circuited, which means that it is guaranteed the second operand is evaluated if and only if the first one is evaluated astrue. The conditionsif (bar && foo)andif (bar) if (foo)are identical.Given that
foois expensive to compute, you should almost definitely checkbarfirst. Even thoughbarwon’t be predictable by the branch predictor very well, that’s a minor effect compared to the computation offoo.Thus the structure should probably be:
Note that all of those constructions mean that we may or may not call
compute(). If you require the function call unconditionally, then you should make it the first check. In that case, the successful branch prediction on the result should be exploited.