当Java虚拟机没有完全预热时,10倍性能差异最有可能发生。如果不进行预热,即使在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倍。
.getClass()
是否成为瓶颈。 猜测并不是解决性能问题的有益方式,除非你能显著降低算法的总体复杂度(例如从N平方操作到对数N操作),并且数据集非常大。 - Merlyn Morgan-Graham