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的幂除以移位?
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- JPA惰性列表上的流 2022-01-01
