按位运算符更快吗?如果是,那为什么呢? [英] Are bitwise operators faster?, if yes then why?
问题描述
如果使用,它将对性能产生多大影响
How much will it affect the performance if I use:
n>>1 instead of n/2
n&1 instead of n%2!=0
n<<3 instead of n*8
n++ instead of n+=1
and so on...
如果确实可以提高性能,请说明原因.
and if it does increase the performance then please explain why.
推荐答案
任何半个体面的编译器都会将两个版本优化成同一件事.例如,GCC编译以下代码:
Any half decent compiler will optimize the two versions into the same thing. For example, GCC compiles this:
unsigned int half1(unsigned int n) { return n / 2; }
unsigned int half2(unsigned int n) { return n >> 1; }
bool parity1(int n) { return n % 2; }
bool parity2(int n) { return n & 1; }
int mult1(int n) { return n * 8; }
int mult2(int n) { return n << 3; }
void inc1(int& n) { n += 1; }
void inc2(int& n) { n++; }
到
half1(unsigned int):
mov eax, edi
shr eax
ret
half2(unsigned int):
mov eax, edi
shr eax
ret
parity1(int):
mov eax, edi
and eax, 1
ret
parity2(int):
mov eax, edi
and eax, 1
ret
mult1(int):
lea eax, [0+rdi*8]
ret
mult2(int):
lea eax, [0+rdi*8]
ret
inc1(int&):
add DWORD PTR [rdi], 1
ret
inc2(int&):
add DWORD PTR [rdi], 1
ret
一个小警告是,在第一个示例中,如果 n
可以为负(如果已签名且编译器无法证明其为非负数),则除法和位移位是不等价的,该部门需要一些额外的说明.除此之外,编译器很聪明,并且它们将使用常量操作数来优化操作,因此使用在逻辑上更有意义,更易读的任何版本.
One small caveat is that in the first example, if n
could be negative (in case that it is signed and the compiler can't prove that it's nonnegative), then the division and the bitshift are not equivalent and the division needs some extra instructions. Other than that, compilers are smart and they'll optimize operations with constant operands, so use whichever version makes more sense logically and is more readable.
这篇关于按位运算符更快吗?如果是,那为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!