x> = 0比x> -1? [英] Is x >= 0 more efficient than x > -1?
问题描述
在C ++中使用int比较 x> = 0
比 x> -1
?
Doing a comparison in C++ with an int is x >= 0
more efficient than x > -1
?
推荐答案
简短答案:不。
更长的答案提供一些教育的洞察力:它完全取决于你的编译器,尽管我打赌,每个正确的编译器为2个表达式创建相同的代码。
longer answer to provide some educational insight: it depends entirely on your compiler, allthough i bet that every sane compiler creates identical code for the 2 expressions.
示例代码:
int func_ge0(int a) {
return a >= 0;
}
int func_gtm1(int a) {
return a > -1;
}
,然后编译并比较生成的汇编代码:
and then compile and compare the resulting assembler code:
% gcc -S -O2 -fomit-frame-pointer foo.cc
这:
yields this:
_Z8func_ge0i:
.LFB0:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
movl 4(%esp), %eax
notl %eax
shrl $31, %eax
ret
.cfi_endproc
vs。
_Z9func_gtm1i:
.LFB1:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
movl 4(%esp), %eax
notl %eax
shrl $31, %eax
ret
.cfi_endproc
(编译器:g ++ - 4.4)
(compiler: g++-4.4)
结论:编译器,专注于算法和数据结构,基准和配置文件真正的瓶颈,如果有疑问:检查编译器的输出。
conclusion: don't try to outsmart the compiler, concentrate on algorithms and data structures, benchmark and profile real bottlenecks, if in doubt: check the output of the compiler.
这篇关于x> = 0比x> -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!