问题描述
我有一条条件语句 expensive_foo()
在99.9%的情况下为假。而且我有一个条件语句 bar
在大约50%的情况下是正确的。
我希望可以采取一些措施如果两个语句都为真,则完成。因此,我几乎可以肯定知道 expensive_foo()
是错误的,我只想在 bar
为真的情况下进行检查。 / p>
下面的代码仅在 bar $ c $时检查
expensive_foo()
c>是真的吗?还是每次都会检查 expensive_foo()
?
if(bar &&昂贵_foo())
{
...
}
或者我需要建立一个这样的结构:
if(bar)
{
if(cheap_foo())
{
...
}
}
逻辑AND运算符&&
短路,这意味着可以保证仅当第一个操作数被评估为 true
时,才评估第二个操作数。 if(bar&& foo)
和 if(bar)if(foo)
的条件是相同的。 / p>
鉴于 foo
的计算成本很高,因此您几乎应该确定 bar $首先。即使
bar
分支预测器无法很好地预测它,但与 foo
。
因此,结构应为:
if( bar)
{
if(bool const foo = compute())//昂贵的
{
// ...
}
}
请注意,所有这些构造意味着我们可能会或可能不会调用 compute()
。如果您需要无条件调用该函数,则应使其成为 first 检查。在这种情况下,应该利用对结果的成功分支预测。
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.
这篇关于C ++条件运算符性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!