public class ArrayCopyTest {
// size = 10;
// size = 100000;
public static final int size = 1000000;
public static void copyByClone(String[] strArray){
long startTime = System.nanoTime();
String[] destArray = strArray.clone();
long endTime = System.nanoTime();
System.out.println("copyByClone cost time is "+(endTime - startTime));
}
public static void copyByLoop(String[] strArray){
long startTime = System.nanoTime();
String[] destArray = new String[size];
for (int i = 0; i < strArray.length; i++){
destArray[i] = strArray[i];
}
long endTime = System.nanoTime();
System.out.println("copyByLoop cost time is "+(endTime - startTime));
}
public static void copyByArrayCopy(String[] strArray){
long startTime = System.nanoTime();
String[] destArray = new String[size];
System.arraycopy(strArray, 0, destArray, 0, strArray.length);
long endTime = System.nanoTime();
System.out.println("copyByArrayCopy cost time is "+(endTime - startTime));
}
public static void copyByCopyof(String[] strArray){
long startTime = System.nanoTime();
String[] destArray = Arrays.copyOf(strArray, strArray.length);
long endTime = System.nanoTime();
System.out.println("copyByCopyof cost time is "+(endTime - startTime));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] strArray = new String[size];
for (int i = 0; i < size; i++){
strArray[i] = "abc";
}
copyByClone(strArray);
copyByLoop(strArray);
copyByArrayCopy(strArray);
copyByCopyof(strArray);
}
}
/*
result:
copyByClone cost time is 10263
copyByLoop cost time is 1642
copyByArrayCopy cost time is 6158
copyByCopyof cost time is 58294
*/
/*
result:
copyByClone cost time is 201980
copyByLoop cost time is 2340831
copyByArrayCopy cost time is 284496
copyByCopyof cost time is 323086
*/
result:
copyByClone cost time is 3116729
copyByLoop cost time is 8657626
copyByArrayCopy cost time is 11609734
copyByCopyof cost time is 2423348
你们可以写代码试试,并不像有人评论的是说无数次实验结果都是哪个性能最高。所以我也弄得不是太明白,希望大神给解答。