自写代码手动测试Java编译器是否会把2优化为位运算以及是否会把对2的取模取余操作优化为位运算

9次阅读

共计 2137 个字符,预计需要花费 6 分钟才能阅读完成。

前言

今天回想起一道 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 s
Shift operations consumed time: 0.264115 s

// 第二次
Division operations consumed time: 1.000502 s
Shift operations consumed time: 0.251574 s

// 第三次
Division operations consumed time: 1.056946 s
Shift 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 s
Shift operations consumed time: 0.003005 s

// 第二次
Modulo operations consumed time: 0.808596 s
Shift operations consumed time: 0.002247 s

// 第三次
Modulo operations consumed time: 0.825826 s
Shift operations consumed time: 0.003162 s

根据耗时,得出结论:java 编译器没有把对 2 的取模 / 取余操作优化为位运算

写在最后

感谢阅读,如果本文陈述的内容存在问题,欢迎和我交流!– JellyfishMIX@qq.com

正文完
 0