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

前言

今天回想起一道java面试题:java

用最有效率的方法算出2乘8等于几?面试

答案是2 << 3,使用位运算,至关于乘以了2^3。bash

跟朋友在这个问题上讨论起来了,有人说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优化为位运算spa

其它的测试

测试java编译器是否会把对2的取模/取余操做优化为位运算

java中取模/取余操做符是%,一般取模运算也叫取余运算,他们都遵循除法法则,返回结果都是左操做数除以右操做数的余数。code

代码

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次:orm

// 第一次
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.comstring

相关文章
相关标签/搜索