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运算),并且数据集非常大,否则猜测不是有效的调试性能问题的方法。 –