前言
在ArrayList扩容机制中注意到,数组的深拷贝有用到两种方法:System.arraycopy()
和Arrays.copyOf()
。
比较
System.arraycopy()
是native
方法,参数需要传递源数组和目标数组。
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
Arrays.copyOf()
方法内部其实调用了System.arraycopy()
方法
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
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;
}
所以Arrays.copyOf()
在数组自动扩容时可以很方便。理论上System.arraycopy()
的性能肯定是优于Arrays.copyOf()
的。但是注意到Arrays.copyOf()
在自动创建数组时使用了源数组的Class
。如果使用System.arraycopy()
进行拷贝操作时源数组和目标数组类型并不完全一致(比如Object[]和String[])时,会额外有类型检查花销[stackflow]。