问题描述
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是否优化了2的幂除以移位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!