4种数组复制方法效率比较
package ind;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = new int[100000000];
int index = 0;
for (int i = 0; i < arr.length; i++) {
arr[index++] = i;
}
System.out.println("for循环逐一复制:" + forLoop(arr));
System.out.println("System.arraycopy:" + systemArrayCopy(arr));
System.out.println("Array.copyOf:" + arrayCopyOf(arr));
System.out.println("使用clone方法:" + cloneMethod(arr));
}
public static int forLoop(int[] arr) {
int[] copy = new int[arr.length];
long start = System.currentTimeMillis();
for (int i = 0; i < copy.length; i++) {
copy[i] = arr[i];
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
public static int systemArrayCopy(int[] arr) {
int[] copy = new int[arr.length];
long start = System.currentTimeMillis();
System.arraycopy(arr, 0, copy, 0, arr.length);
long end = System.currentTimeMillis();
return (int) (end - start);
}
public static int arrayCopyOf(int[] arr) {
int[] copy = new int[arr.length];
long start = System.currentTimeMillis();
copy = Arrays.copyOf(arr, arr.length);
long end = System.currentTimeMillis();
return (int) (end - start);
}
public static int cloneMethod(int[] arr) {
int[] copy = new int[arr.length];
long start = System.currentTimeMillis();
copy = arr.clone();
long end = System.currentTimeMillis();
return (int) (end - start);
}
}
System.arraycopy是native方法,效率最高
但其他几个好像和一些答案不太一样...
有没有大佬解答疑惑~