这个测试
for (;;) {
int[] a = new int[10];
System.gc();
long t0 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
// int[] b = a.clone();
int[] b = Arrays.copyOf(a,a.length);
}
System.out.println(System.currentTimeMillis() - t0);
}
显示Arrays.copyOf约为50ms,克隆显示约160ms.克隆是一种特殊的原生方法来制作副本,为什么它这么慢?
我在HotSpot Client JVM 1.7.0_11-b21上运行测试.请注意,当阵列大小增加时,clone和copyOf之间的差异会消失.
解决方法
我在你的系统上运行你的代码:它们之间几乎没有区别.两者的时钟都在大约30毫秒.我的测试是在OpenJDK 7上进行的.
为了确认我也通过Caliper运行它,并使用更大的数组来强调实际的复制性能:
public class Performance extends SimpleBenchmark {
final int[] source = new int[1000];
public int timeClone(int reps) {
int sum = 0;
for (int i = reps; i > 0; i--)
sum += source.clone().length;
return sum;
}
public int timecopyOf(int reps) {
int sum = 0;
for (int i = reps; i > 0; i--)
sum += Arrays.copyOf(source,source.length).length;
return sum;
}
public static void main(String... args) {
Runner.main(Performance.class,args);
}
}
结果:
0% Scenario{vm=java,trial=0,benchmark=Clone} 2141.70 ns; σ=5416.80 ns @ 10 trials
50% Scenario{vm=java,benchmark=copyOf} 2168.38 ns; σ=1545.85 ns @ 10 trials
benchmark us linear runtime
Clone 2.14 =============================
copyOf 2.17 ==============================
vm: java
trial: 0
根据请求,这里的数组大小为10:
0% Scenario{vm=java,benchmark=Clone} 30.07 ns; σ=2.12 ns @ 10 trials
50% Scenario{vm=java,benchmark=copyOf} 29.34 ns; σ=161.38 ns @ 10 trials
benchmark ns linear runtime
Clone 30.1 ==============================
copyOf 29.3 =============================