考慮下面的代碼片段,從而產生一個UUID.randomUUID()
,我得到下面的性能結果(以毫秒爲單位):爲什麼對UUID.randomUUID()的初始調用很慢?
public static void main(String[] args) {
long tmp = System.currentTimeMillis();
UUID.randomUUID();
tmp = printDiff(tmp);
UUID.randomUUID();
tmp = printDiff(tmp);
UUID.randomUUID();
tmp = printDiff(tmp);
UUID.randomUUID();
tmp = printDiff(tmp);
}
private static long printDiff(final long previousTimestamp) {
long tmp = System.currentTimeMillis();
System.out.printf("%s%n", tmp - previousTimestamp);
return tmp;
}
結果:
971
6
0
0
JDK: 1.8 OS : Windows 7
爲什麼只有最初的通話需要這麼長時間嗎? (接近1秒!)
@ 4castle它不是,只有4調用這裏,沒有JIT – Eugene
的SecureRandom的初始化可以在Windows上很慢,由於網絡接口掃描等,參見[這個問題](HTTP://計算器。 com/questions/38942514/simple-java-program-100-times-after-plug-in-usb-hotspot)瞭解詳情。 – apangin