10倍差異最有可能的情況是JVM沒有完全預熱。如果你不這樣做,即使在Java中,你也可以看到超過10倍的性能差異。我會嘗試以10,000的批次運行,並忽略前幾次運行。
public static void main(String... args) throws IOException {
timeObjectGraph("First run", 1);
timeObjectGraph("Second run", 2);
timeObjectGraph("Next thousand", 1000);
for (int i = 0; i < 5; i++)
timeObjectGraph("Next ten thousand", 10000);
}
static int dontOptimiseAway = 0;
public static void timeObjectGraph(String desc, int runs) throws IOException {
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(Calendar.getInstance());
oos.close();
dontOptimiseAway = out.toByteArray().length;
}
long time = System.nanoTime() - start;
System.out.printf("%s took an avg time of %,d ns%n", desc, time/runs);
}
打印
First run took an avg time of 37,509,488 ns
Second run took an avg time of 439,054 ns
Next thousand took an avg time of 185,242 ns
Next ten thousand took an avg time of 41,698 ns
Next ten thousand took an avg time of 19,981 ns
Next ten thousand took an avg time of 11,541 ns
Next ten thousand took an avg time of 13,451 ns
Next ten thousand took an avg time of 11,289 ns
從第一個到最後運行,其性能已通過的3000倍
的因素@ xlc0212提高也不是任何其他人不理解Java的! ;) – cheeken
@cheeken它取決於JVM,沒有JIT,我記得我從某處讀過Java比python慢甚至更慢 –
老實說這聽起來像是一個沒有問題的東西。是否值得您花時間對已棄用的代碼進行基準測試和分析?除非你這樣做,否則無法知道'.getClass()'是瓶頸。除非可以顯着降低算法的總體複雜度(即從N平方運算變爲log-N運算),並且數據集非常大,否則猜測不是有效的調試性能問題的方法。 –