数组复制的方法
- for()循环方法;
- Object.clone()方法;
- Arrays.copyOf()方法;
- System.arraycopy()方法(推荐使用)
- 方法性能比较
1、for()循环方法
代码灵活,但效率低。
2、Object.clone()方法
从源码来看同样也是native方法,但返回为Object类型,所以赋值时将发生强转,所以效率不如之后两种。
(仅仅是在百万数据级别的情况下)
protected native Object clone() throws CloneNotSupportedException;
3、Arrays.copyOf()方法
同样看源码,它的实现还是基于System.arraycopy(),所以效率自然低于System.arraycpoy()。
(仅仅是在百万数据级别的情况下)
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;
}
4、System.arraycopy()方法(推荐使用)
通过源码可以看到,其为native方法,即原生态方法。自然效率更高。
(仅仅是在百万数据级别的情况下)
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
5、方法性能测试比较
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) {
//int length = 10000000; //千万级别
int length = 8000000; //百万级别
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()循环方法耗费时间:30ms
long start = System.currentTimeMillis();
for (int index = 0; index < length; index++) {
arr2[index] = arr[index];
}
long end = System.currentTimeMillis();
System.out.println("for()循环方法耗费时间:" + (end - start) + "ms");
//Object.clone()方法耗费时间:15ms
start = System.currentTimeMillis();
arr2 = arr.clone();
end = System.currentTimeMillis();
System.out.println("Object.clone()方法耗费时间:" + (end - start) + "ms");
//Arrays.copyOf()方法耗费时间:14ms
start = System.currentTimeMillis();
arr2 = Arrays.copyOf(arr, length);
end = System.currentTimeMillis();
System.out.println("Arrays.copyOf()方法耗费时间:" + (end - start) + "ms");
//System.arraycopy()方法耗费时间:10ms
start = System.currentTimeMillis();
System.arraycopy(arr, 0, arr2, 0, length);
end = System.currentTimeMillis();
System.out.println("System.arraycopy()方法耗费时间:" + (end - start) + "ms");
}
}
数据量是百万级别的情况下:
数据量是千万级别的情况下: