当对象较小时,创建对象的速度非常快,并且没有 GC 成本。
final int batch = 1000 * 1000;
Double[] doubles = new Double[batch];
long start = System.nanoTime();
for (int j = 0; j < batch; j++)
doubles[j] = (double) j;
long time = System.nanoTime() - start;
System.out.printf("Average object allocation took %.1f ns.%n", (double) time/batch);
打印与-verbosegc
Average object allocation took 13.0 ns.
注意:没有发生 GC。然而,增加大小,程序需要等待在 GC 中复制内存。
final int batch = 10 *1000 * 1000;
prints
[GC 96704K->94774K(370496K), 0.0862160 secs]
[GC 191478K->187990K(467200K), 0.4135520 secs]
[Full GC 187990K->187974K(618048K), 0.2339020 secs]
Average object allocation took 78.6 ns.
我怀疑你的分配速度相对较慢,因为你正在执行GC。解决这个问题的一种方法是增加应用程序可用的内存。 (虽然这可能只是推迟成本)
如果我再次运行它-verbosegc -XX:NewSize=1g
Average object allocation took 9.1 ns.