java – Null/Object和Null/Null比较效率

This question引导我做一些测试:

public class Stack
{
    public static void main(String[] args)
    {
        Object obj0 = null;
        Object obj1 = new Object();
        long start;
        long end;
        double difference;  
        double differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (obj0 == null);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);
        differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (null == obj0);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);
        differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (obj1 == null);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);
        differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (null == obj1);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);      
    }
}

other post相切,有趣的是,当我们比较的对象被初始化时,比较的速度要快得多.每个输出中的前两个数字是Object为null时,后两个数字是Object初始化时的数字.在所有30次执行中,我运行了21次额外的程序执行,初始化Object时的比较速度要快得多.这里发生了什么?

最佳答案
如果将最后两个循环移动到开头,您将得到相同的结果,因此比较无关紧要.

这都是关于JIT编译器热身的.在前两个循环中,java以解释字节码开始.在一些迭代之后,它确定代码路径是“热”的,因此它将它编译为机器代码并删除无效的循环,因此您基本上测量System.nanotime和双算术.

我不确定为什么两个循环很慢.我认为在找到两个热路径后,它决定优化整个方法.

转载注明原文:java – Null/Object和Null/Null比较效率 - 代码日志