for()循環(huán)方法
代碼靈活,但效率低。
System.arraycopy()方法(推薦使用)
該方法是淺拷貝,也就是說(shuō)對(duì)于非基本類(lèi)型而言,拷貝的是對(duì)象的引用,而不是去新建一個(gè)新的對(duì)象。
通過(guò)源碼可以看到,其為 native方法,即原生態(tài)方法,是調(diào)用底層的 C 或者 C++ 實(shí)現(xiàn)的,自然效率更高。
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
Arrays.copyOf()方法
同樣看源碼,它的實(shí)現(xiàn)還是基于 System.arraycopy(),所以效率自然低于 System.arraycpoy()。 同樣,這個(gè)方法也是淺拷貝。
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;
}
Object.clone()方法
該方法比較特殊,對(duì)于對(duì)象而言,它是深拷貝,但是對(duì)于數(shù)組而言,它是淺拷貝。
從源碼來(lái)看是 native 方法,所以是調(diào)用了 C 或者 C++ 代碼。
protected native Object clone() throws CloneNotSupportedException;
方法性能測(cè)試比較
import java.util.Arrays;
import java.util.Random;
/**
* 數(shù)組復(fù)制的方法比較
*
* @author TinyDolphin
* 2017/11/1 15:40.
*/
public class Main {
public static void main(String[] args) {
// int length = 10000000; // 千萬(wàn)級(jí)別
int length = 8000000; // 百萬(wàn)級(jí)別
Integer[] arr = new Integer[length];
Integer[] arr2 = new Integer[length];
for (int index = 0; index < length; index++) {
arr[index] = new Random().nextInt(length) + 1;
}
// for() 循環(huán)方法
long start = System.currentTimeMillis();
for (int index = 0; index < length; index++) {
arr2[index] = arr[index];
}
long end = System.currentTimeMillis();
System.out.println("for()循環(huán)方法耗費(fèi)時(shí)間:" + (end - start) + "ms");
// Object.clone() 方法
start = System.currentTimeMillis();
arr2 = arr.clone();
end = System.currentTimeMillis();
System.out.println("Object.clone()方法耗費(fèi)時(shí)間:" + (end - start) + "ms");
// Arrays.copyOf() 方法
start = System.currentTimeMillis();
arr2 = Arrays.copyOf(arr, length);
end = System.currentTimeMillis();
System.out.println("Arrays.copyOf()方法耗費(fèi)時(shí)間:" + (end - start) + "ms");
// System.arraycopy() 方法
start = System.currentTimeMillis();
System.arraycopy(arr, 0, arr2, 0, length);
end = System.currentTimeMillis();
System.out.println("System.arraycopy()方法耗費(fèi)時(shí)間:" + (end - start) + "ms");
}
}
數(shù)據(jù)量百萬(wàn)級(jí)別的情況下:

百萬(wàn)級(jí)別測(cè)試結(jié)果
數(shù)據(jù)量是千萬(wàn)級(jí)別的情況下:

千萬(wàn)級(jí)別測(cè)試結(jié)果