我想就为什么
clone()复制数组比
System.arraycopy(..)其他方法最快的方法提出一些意见:
1.
clone()在将源数组复制到此处提供的目标数组之前,不必进行类型检查。它只是简单地分配新的内存空间并为其分配对象。另一方面,
System.arraycopy(..)检查类型,然后复制数组。
2.
clone()还破坏了消除冗余归零的优化。如您所知,Java中每个分配的数组都必须使用
0s或各自的默认值进行初始化。但是,如果JIT看到该数组在创建后立即被填充,则可以避免将该数组清零。与使用现有
0s或相应的默认值更改复印值相比,这无疑使其速度更快。使用时,
System.arraycopy(..)花费大量时间清除和复制初始化的数组。为此,我已经执行了一些基准测试。
@BenchmarkMode(Mode.Throughput)@Fork(1)@State(Scope.Thread)@Warmup(iterations = 10, time = 1, batchSize = 1000)@Measurement(iterations = 10, time = 1, batchSize = 1000)public class BenchmarkTests { @Param({"1000","100","10","5", "1"}) private int size; private int[] original; @Setup public void setup() { original = new int[size]; for (int i = 0; i < size; i++) { original[i] = i; } } @Benchmark public int[] SystemArrayCopy() { final int length = size; int[] destination = new int[length]; System.arraycopy(original, 0, destination, 0, length); return destination; } @Benchmark public int[] arrayClone() { return original.clone(); }}输出:
Benchmark (size) Mode Cnt Score Error UnitsArrayCopy.SystemArrayCopy 1 thrpt 10 26324.251 ± 1532.265 ops/sArrayCopy.SystemArrayCopy 5 thrpt 10 26435.562 ± 2537.114 ops/sArrayCopy.SystemArrayCopy10 thrpt 10 27262.200 ± 2145.334 ops/sArrayCopy.SystemArrayCopy 100 thrpt 10 10524.117 ± 474.325 ops/sArrayCopy.SystemArrayCopy 1000 thrpt 10 984.213 ± 121.934 ops/sArrayCopy.arrayClone 1 thrpt 10 55832.672 ± 4521.112 ops/sArrayCopy.arrayClone 5 thrpt 10 48174.496 ± 2728.928 ops/sArrayCopy.arrayClone 10 thrpt 10 46267.482 ± 4641.747 ops/sArrayCopy.arrayClone 100 thrpt 10 19837.480 ± 364.156 ops/sArrayCopy.arrayClone 1000 thrpt 10 1841.145 ± 110.322 ops/s
根据输出,我得到的
clone速度几乎是以前的两倍
System.arraycopy(..)
3.
此外,
clone()由于不需要进行任何VM调用(与一样
System.arraycopy()),因此使用手动复制方法(如结果)到更快的输出中。



