前言
今天回想起一道java面试题:
用最有效率的方法算出2乘8等于几?
答案是2 << 3,使用位运算,相当于乘以了2^3。
跟朋友在这个问题上讨论起来了,有人说java的编译器会把/2,/4,/8这种涉及2的幂的运算,优化为位运算。在网上查询发现没有多少相关文章,抱着探究精神,决定手动测试一番。
进行测试
代码
public class Main { public static void main(String[] args) { Main.testDivision(); Main.testShift(); } /** * 除法测试 */ private static void testDivision() { long startTime = System.nanoTime(); int tem = Integer.MAX_VALUE; for (int i = 0; i <1000000000 ; i++) { tem = tem / 2; } long endTime = System.nanoTime(); System.out.println(String.format("Division operations consumed time: %f s", (endTime - startTime) / 1000000000.0)); } /** * 位运算测试 */ private static void testShift() { long startTime = System.nanoTime(); int tem = Integer.MAX_VALUE; for (int i = 0; i <1000000000 ; i++) { tem = tem >> 1; } long endTime = System.nanoTime(); System.out.println(String.format("Shift operations consumed time: %f s", (endTime - startTime) / 1000000000.0)); }}
测试结果
总共测试了3次:
// 第一次Division operations consumed time: 1.023045 sShift operations consumed time: 0.264115 s// 第二次Division operations consumed time: 1.000502 sShift operations consumed time: 0.251574 s// 第三次Division operations consumed time: 1.056946 sShift operations consumed time: 0.262253 s
根据耗时,得出结论:java编译器没有把/2优化为位运算。
其它的测试
测试java编译器是否会把对2的取模/取余操作优化为位运算
java中取模/取余操作符是%,通常取模运算也叫取余运算,他们都遵循除法法则,返回结果都是左操作数除以右操作数的余数。
代码
public class Main { public static void main(String[] args) { Main.testModulo(); Main.testShift(); } /** * 取模测试 */ private static void testModulo() { long startTime = System.nanoTime(); int tem = Integer.MAX_VALUE; for (int i = 0; i <1000000000 ; i++) { tem = tem % 2; } long endTime = System.nanoTime(); System.out.println(String.format("Modulo operations consumed time: %f s", (endTime - startTime) / 1000000000.0)); } /** * 位运算测试 */ private static void testShift() { long startTime = System.nanoTime(); int tem = Integer.MAX_VALUE; for (int i = 0; i <1000000000 ; i++) { tem = tem & 1; } long endTime = System.nanoTime(); System.out.println(String.format("Shift operations consumed time: %f s", (endTime - startTime) / 1000000000.0)); }}
测试结果
总共测试了3次:
// 第一次Modulo operations consumed time: 0.813894 sShift operations consumed time: 0.003005 s// 第二次Modulo operations consumed time: 0.808596 sShift operations consumed time: 0.002247 s// 第三次Modulo operations consumed time: 0.825826 sShift operations consumed time: 0.003162 s
根据耗时,得出结论:java编译器没有把对2的取模/取余操作优化为位运算。
写在最后
感谢阅读,如果本文陈述的内容存在问题,欢迎和我交流!-- JellyfishMIX@qq.com