java - .clone() 还是 Arrays.copyOf()?

标签 java immutability

为了减少可变性,我们是否应该使用

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) );
}

最佳答案

使用 jmh 更新

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

原帖

我对性能进行了快速测试:cloneSystem.arrayCopyArrays.copyOf 的性能非常相似(jdk 1.7.06 , 服务器虚拟机)。

JIT之后的详细信息(以毫秒为单位):

clone: 68
arrayCopy: 68
Arrays.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];
}

关于java - .clone() 还是 Arrays.copyOf()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157300/

相关文章:

java - 如何将2048位的BigInteger分割成固定数量的64位的字?

java - 如何在java中从Html中的Div标签中提取文本

javascript - 使用不变性助手更新 React 状态下的数组对象

c# - 为什么 C# 不允许只读局部变量?

java - 在客户端上生成 RMI stub

java - 线程中的异步回调

java - 如何在循环中调用可完成的 future 并组合所有结果?

rust - 即使声明为可变的,变量也被认为是不可变的

java - 为什么库更喜欢在边缘情况下重新计算不可变对象(immutable对象)的哈希码?

java - 如何实现使用模板的界面?