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 倍