Java是否通过两个幂的乘法优化除法? [英] Does Java optimize division by powers of two to bitshifting?

查看:210
本文介绍了Java是否通过两个幂的乘法优化除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java编译器的JIT编译器是否以2的常数乘以bithifting来优化除法或乘法?

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编译器不这样做,因为它不能确定将会。为什么这么重要?负整数上的位移产生与普通除法不同的结果。在这里您可以看到演示:这个简单的测试

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆