數組複制效率的比較
java中數組複制的方式,有以下幾種
(1)System.arraycopy();
(2)Arrays.copyOf();
(3)clone();
(4)for循環
今天我們比較一下這四者的效率
一、System.arraycopy()
此方法的源碼如下:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
可見此方法是一個本地方法,方法對應的實作不在目前檔案裡,而是在其他語言實作的的檔案的,比如C、C++中。
使用本地方法,案例來說效率應該最高,稍後進行效率測試。
二、Arrays.copyOf()
此方法的源碼如下:
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;
}
可以看得出來,本質上調用的是System.arraycopy()方法,也就是前一種方法,那麼效率肯定比不上前一種數組複制方法。
三、clone()
此方法的源碼如下:
protected native Object clone() throws CloneNotSupportedException;
這個方法是Object類中的一個本地方法,這裡雖然傳回Object,看着需要強制類型轉換,但Object子類重寫了這個方法,會傳回相應的類型。
四、for循環
最簡單粗暴的一種方式,循環原始數組并直接指派到目标數組中。
五、四種的比較
他們之間的效率比較需要從原始數組的大小出發。
先貼出比較的代碼:
package day0908;
import java.util.Arrays;
public class TestArrayCopy {
public static void testSystemArrayCopy(String[] orginal) {
long start_time = System.nanoTime();
String[] target = new String[orginal.length];
System.arraycopy(orginal, 0, target, 0, target.length);
long end_time = System.nanoTime();
System.out.println("使用System.arraycopy方法耗時:" + (end_time - start_time));
}
public static void testArraysCopyOf(String[] orginal) {
long start_time = System.nanoTime();
String[] target = new String[orginal.length];
target = Arrays.copyOf(orginal, orginal.length);
long end_time = System.nanoTime();
System.out.println("使用Arrays.copyOf方法耗時:" + (end_time - start_time));
}
public static void testClone(String[] orginal) {
long start_time = System.nanoTime();
String[] target = new String[orginal.length];
target = orginal.clone();
long end_time = System.nanoTime();
System.out.println("使用clone方法耗時:" + (end_time - start_time));
}
public static void testFor(String[] orginal) {
long start_time = System.nanoTime();
String[] target = new String[orginal.length];
for (int i = 0; i < orginal.length; i++) {
target[i] = orginal[i];
}
long end_time = System.nanoTime();
System.out.println("使用for循環耗時:" + (end_time - start_time));
}
public static void main(String args[]) {
//需要改變原始數組的大小
String[] original = new String[100];
for (int i = 0; i < original.length; i++) {
original[i] = "abcd";
}
System.out.println("原始數組的大小:" + original.length);
testSystemArrayCopy(original);
testArraysCopyOf(original);
testClone(original);
testFor(original);
}
}
比較他們之間的效率需要從目标數組的大小出發。
【1】目标數組是個小數組,長度在200以内
四種方式的效率:
可以看得出:Arrays.copyOf()的效率最差,其餘三種效率差異不大。
【2】目标是個中等數組,長度以千為機關。
四種方式的效率:
可以看得出,System.arraycopy()與clone()方式差異不大,使用for循環的方式,耗時比之前的情況變得嚴重起來。
【3】目标數組是個大型數組,長度以萬為機關。
四種方式的效率:
可以看得出,此時System.arraycopy()方法的效率最高,且數組長度在此基礎增加時,此方法效率還是最高,而for循環的效率在這種情況下表現得十分糟糕。
六、總結
(1)原始數組長度不管是多少的時候,Arrays.copyOf()的效率都比System.arraycopy()差。
(2)原始數組長度比較小的時候,幾百以内,for循環表現十分優異,并随着數組長度的增加,效率越來越低,是以,for循環适合于小型數組。