Java 是否将除法以二的幂优化为移位? [英] Does Java optimize division by powers of two to bitshifting?
问题描述
Java 编译器是还是 JIT 编译器通过 2 的常数幂优化除法或乘法以实现位移?
Does the Java compiler or the JIT compiler optimize divisions or multiplications by a constant power of two down to bitshifting?
例如,下面两个语句是否优化为相同?
For example, are the following two statements optimized to be the same?
int median = start + (end - start) >>> 1;
int median = start + (end - start) / 2;
(基本上这个问题 但对于 Java)
(basically this question but for Java)
推荐答案
不,Java 编译器不会这样做,因为它无法确定 (end - start)的符号是什么代码> 将是.为什么这很重要?负整数的位移产生与普通除法不同的结果.在这里你可以看到一个演示:这个简单的测试:
No, the Java compiler doesn't do that, because it can't be sure on what the sign of (end - start)
will be. Why does this matter? Bit shifts on negative integers yield a different result than an ordinary division. Here you can see a demo: this simple test:
System.out.println((-10) >> 1); // prints -5
System.out.println((-11) >> 1); // prints -6
System.out.println((-11) / 2); // prints -5
另请注意,我使用了 >>
而不是 >>>
.>>>>
是无符号位移,而 >>>
是有符号的.
Also note that I used >>
instead of >>>
. A >>>
is an unsigned bitshift, while >>
is signed.
System.out.println((-10) >>> 1); // prints 2147483643
@Mystical:我写了一个基准测试,表明编译器/JVM 没有进行优化:https://ideone.com/aKDShA
这篇关于Java 是否将除法以二的幂优化为移位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!