.clone() or Arrays.copyOf()?

2022-08-31 22:11:45

为了降低可变性,我们是否应该使用

public void setValues(String[] newVals) {

     this.vals = ( newVals == null ? null : newVals.clone() );
}

public void setValues(String[] newVals) {

     this.vals = ( newVals == null ? null : Arrays.copyOf(newVals, newVals.length) );
}

答案 1

使用 jmh 进行更新

使用jmh,我得到了类似的结果,除了这似乎稍微好一点。clone

原文

我运行了一个性能的快速测试:,并且具有非常相似的性能(jdk 1.7.06,服务器vm)。cloneSystem.arrayCopyArrays.copyOf

有关详细信息(以毫秒为单位),在 JIT 之后:

克隆: 68
数组复制: 68
数组.copyOf: 68

测试代码:

public static void main(String[] args) throws InterruptedException,
        IOException {
    int sum = 0;
    int[] warmup = new int[1];
    warmup[0] = 1;
    for (int i = 0; i < 15000; i++) { // triggers JIT
        sum += copyClone(warmup);
        sum += copyArrayCopy(warmup);
        sum += copyCopyOf(warmup);
    }

    int count = 10_000_000;
    int[] array = new int[count];
    for (int i = 0; i < count; i++) {
        array[i] = i;
    }

    // additional warmup for main
    for (int i = 0; i < 10; i++) {
        sum += copyArrayCopy(array);
    }
    System.gc();
    // copyClone
    long start = System.nanoTime();
    for (int i = 0; i < 10; i++) {
        sum += copyClone(array);
    }
    long end = System.nanoTime();
    System.out.println("clone: " + (end - start) / 1000000);
    System.gc();
    // copyArrayCopy
    start = System.nanoTime();
    for (int i = 0; i < 10; i++) {
        sum += copyArrayCopy(array);
    }
    end = System.nanoTime();
    System.out.println("arrayCopy: " + (end - start) / 1000000);
    System.gc();
    // copyCopyOf
    start = System.nanoTime();
    for (int i = 0; i < 10; i++) {
        sum += copyCopyOf(array);
    }
    end = System.nanoTime();
    System.out.println("Arrays.copyOf: " + (end - start) / 1000000);
    // sum
    System.out.println(sum);
}

private static int copyClone(int[] array) {
    int[] copy = array.clone();
    return copy[copy.length - 1];
}

private static int copyArrayCopy(int[] array) {
    int[] copy = new int[array.length];
    System.arraycopy(array, 0, copy, 0, array.length);
    return copy[copy.length - 1];
}

private static int copyCopyOf(int[] array) {
    int[] copy = Arrays.copyOf(array, array.length);
    return copy[copy.length - 1];
}

答案 2

还要考虑使用“clone()”的安全性。一类众所周知的攻击使用用恶意代码覆盖对象的“clone()”方法的类。例如,CVE-2012-0507(Mac OS上的“闪回”攻击)基本上是通过将“.clone()”调用替换为“.copyOf”调用来解决的。

关于“clone()”过时性的其他讨论可以在StackOverflow上找到:对象克隆,实现可克隆接口