以下哪一种技术是整数除2的最佳选择,为什么?
技巧1:
x = x >> 1;
技巧2:
x = x / 2;
这里x是整数。
以下哪一种技术是整数除2的最佳选择,为什么?
技巧1:
x = x >> 1;
技巧2:
x = x / 2;
这里x是整数。
当前回答
我们有很多理由支持使用x = x / 2;以下是一些例子:
it expresses your intent more clearly (assuming you're not dealing with bit twiddling register bits or something) the compiler will reduce this to a shift operation anyway even if the compiler didn't reduce it and chose a slower operation than the shift, the likelihood that this ends up affecting your program's performance in a measurable way is itself vanishingly small (and if it does affect it measurably, then you have an actual reason to use a shift) if the division is going to be part of a larger expression, you're more likely to get the precedence right if you use the division operator: x = x / 2 + 5; x = x >> 1 + 5; // not the same as above signed arithmetic might complicate things even more than the precedence problem mentioned above to reiterate - the compiler will already do this for you anyway. In fact, it'll convert division by a constant to a series of shifts, adds, and multiplies for all sorts of numbers, not just powers of two. See this question for links to even more information about this.
简而言之,当你真正想要进行乘法或除法运算时,编写移位代码并没有什么好处,除了可能会增加引入错误的可能性。自从编译器不够聪明到在适当的时候优化这类事情到移位以来,已经过去了。
其他回答
使用除法(/),假设这样更清楚。编译器将相应地进行优化。
只是加了一个注释
在一些基于vm的语言中,x *= 0.5通常会更快——尤其是actionscript,因为变量不需要被检查是否除以0。
X = X / 2;是合适的代码使用..但是一个操作取决于你自己的程序,你想要产生怎样的输出。
使用x = x / 2;或x /= 2;因为将来有可能会有一个新的程序员使用它。因此,他更容易发现代码行中发生了什么。每个人可能都不知道这种优化。
第一个看起来像除法吗?不。如果你想除法,用x / 2。如果可能的话,编译器可以优化它使用位移位(它被称为强度减少),这使得它成为一个无用的微优化,如果你自己做它。