【发布时间】:2009-03-01 20:58:53
【问题描述】:
我有这样的代码,但我觉得有点难以阅读:
// code1
if( (expensiveOperation1() && otherOperation() && foo())
|| (expensiveOperation2() && bar() && baz()) {
// do something
}
我只是将其更改为以下内容,以使其更具可读性:
// code2
const bool expr1 = expensiveOperation1() && otherOperation() && foo();
const bool expr2 = expensiveOperation2() && bar() && baz();
if(expr1 || expr2){
// one of the conditions met
}
但是我现在应该关注效率吗?
我的意思是,在code1 中,如果第一个连接子句得到满足,那么它甚至不会费心去看第二个,因为很明显该陈述将是正确的。
但在我更易读的示例中,cond1 和 cond2 都必须计算。或者如果 expr2 没有在其他任何地方使用,编译器是否足够聪明,可以将我的 code2 更改为 code1?
【问题讨论】:
-
我正在使用 gcc/g++(准确地说是 g++ v3.4)。
标签: c++ c optimization compiler-construction performance