Does Java optimize division by powers of two to bitshifting?(Java是否优化了2的幂除以移位?)
问题描述
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的幂除以移位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java是否优化了2的幂除以移位?
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
