java - : System. arraycopy 或 Arrays.copyOf 哪个更有效?

标签 java arrays performance

ArrayList 中的 toArray 方法,Bloch 使用 System.arraycopyArrays.copyOf 来复制一个数组。

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents:
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

我如何比较这两种复制方法以及何时应该使用哪种方法?

最佳答案

不同的是,Arrays.copyOf 不仅复制元素,还创建一个新数组。 System.arraycopy 复制到现有数组中。

这是 Arrays.copyOf 的源代码,您可以看到它在内部使用 System.arraycopy 来填充新数组:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

关于java - : System. arraycopy 或 Arrays.copyOf 哪个更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2589741/

相关文章:

java 8 减少累加器返回类型

c++ - 从 C++ 中的函数返回多个数组

javascript - 使用 JQuery 从模态( Bootstrap )传递输入数组

c - 我正在尝试解决这个问题,我已经尝试过,但我不知道如何通过代码或逻辑解决这个问题

java - Java 中小型不可变对象(immutable对象)的缓存策略?

java - jobConf 类是什么?它有什么作用?

Java无效的流头问题

java - 2D volatile 数组 : will self-assignment help or do I need AtomicIntegerArray?

javascript - 更有效的方法来完成这个?

performance - Sitecore 的子布局渲染统计数据不正确吗?