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 as true. The conditions if (bar && foo) and if (bar) if (foo) are identical.
Given that foo is expensive to compute, you should almost definitely check bar first. Even though bar won't be predictable by the branch predictor very well, that's a minor effect compared to the computation of foo.
Thus the structure should probably be:
if (bar)
{
if (bool const foo = compute()) // expensive
{
// ...
}
}
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.
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