为什么clone()是复制数组的最佳方法?


问题内容

这对我来说是一个耻辱,但我不知道:

您应该使用克隆来复制阵列,因为通常这是最快的方法。

如Josh Bloch在此博客中所述:http :
//www.artima.com/intv/bloch13.html

我一直都习惯System.arraycopy(...)。两种方法都是本机的,所以可能没有深入研究我不知道的库来源,为什么会这样。

我的问题很简单:为什么这是 最快的 方法?
有什么区别System.arraycopy此处
说明了差异,但未回答为何乔什·布洛赫(JoshBloch)认为clone()这是最快的方法。


问题答案:

我想就为什么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  Units
ArrayCopy.SystemArrayCopy            1  thrpt   10   26324.251 ± 1532.265  ops/s
ArrayCopy.SystemArrayCopy            5  thrpt   10   26435.562 ± 2537.114  ops/s
ArrayCopy.SystemArrayCopy           10  thrpt   10   27262.200 ± 2145.334  ops/s
ArrayCopy.SystemArrayCopy          100  thrpt   10   10524.117 ±  474.325  ops/s
ArrayCopy.SystemArrayCopy         1000  thrpt   10     984.213 ±  121.934  ops/s
ArrayCopy.arrayClone                 1  thrpt   10   55832.672 ± 4521.112  ops/s
ArrayCopy.arrayClone                 5  thrpt   10   48174.496 ± 2728.928  ops/s
ArrayCopy.arrayClone                10  thrpt   10   46267.482 ± 4641.747  ops/s
ArrayCopy.arrayClone               100  thrpt   10   19837.480 ±  364.156  ops/s
ArrayCopy.arrayClone              1000  thrpt   10    1841.145 ±  110.322  ops/s

根据输出,我得到的clone速度几乎是以前的两倍System.arraycopy(..)

3.
此外,clone()由于不需要进行任何VM调用(与一样System.arraycopy()),因此使用手动复制方法(如结果)到更快的输出中。