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
被初始化时,比较的速度有多快。每个输出中的前两个数字是Object
为null
时,后两个数字是Object
初始化时的数字。在所有30次执行中,我运行了21次额外的程序执行,Object
初始化时的比较速度要快得多。这里发生了什么?
答案 0 :(得分:3)
如果将最后两个循环移到开头,您将得到相同的结果,因此比较无关紧要。
这是关于JIT编译器预热的全部内容。在前2个循环中,java
以解释字节码开始。在一些迭代之后,它确定代码路径是“热”的,因此它将其编译为机器代码并删除无效的循环,因此您基本上测量System.nanotime
和double
算术。
我不确定为什么两个循环很慢。我认为在找到两条热门路径后,它决定优化整个方法。