之前看到很多问题以及很多博客都有讨论java数组拷贝的效率问题,一般都是讨论如下几种方法
int[] b=a.clone();
System.arraycopy(a, 0, b, 0, n);
int[] b=Arrays.copyOf(a, n);
int[] b=Arrays.copyOfRange(a, 0, n);
for
下面做了个测试:拷贝的数组长度为10000个int型数据
测试代码如下:
package test;
import java.util.Arrays;
public class ArrayClone {
public static void testClone() {
int n=10000;
int[] a= new int[n];
for(int i=0;i<n;i++) {
a[i]=i;
}
long beginTime = System.nanoTime();
int[] b=a.clone();
long endTime = System.nanoTime();
System.out.println("a.clone()运行了"+(endTime-beginTime)+"ns");
System.out.println(b[n-1]);
}
public static void testSystemArrayCopy() {
int n=10000;
int[] a= new int[n];
for(int i=0;i<n;i++) {
a[i]=i;
}
int[] b= new int[n];
long beginTime = System.nanoTime();
// 参数含义:(原数组, 原数组的开始位置, 目标数组, 目标数组的开始位置, 拷贝个数)
System.arraycopy(a, 0, b, 0, n);
long endTime = System.nanoTime();
System.out.println("System.arraycopy()运行了"+(endTime-beginTime)+"ns");
System.out.println(b[n-1]);
}
//Arrays.copyOf底层其实也是用的System.arraycopy
public static void testArraysCopyof() {
int n=10000;
int[] a= new int[n];
for(int i=0;i<n;i++) {
a[i]=i;
}
long beginTime = System.nanoTime();
// 参数含义:(原数组,拷贝的个数)
int[] b=Arrays.copyOf(a, n);
long endTime = System.nanoTime();
System.out.println("Arrays.copyOf()运行了"+(endTime-beginTime)+"ns");
System.out.println(b[n-1]);
}
//Arrays.copyOfRange底层其实也是用的System.arraycopy,只不过封装了一个方法
public static void testCopyOfRange() {
int n=10000;
int[] a= new int[n];
for(int i=0;i<n;i++) {
a[i]=i;
}
long beginTime = System.nanoTime();
// 参数含义:(原数组,开始位置,拷贝的个数)
int[] b=Arrays.copyOfRange(a, 0, n);
long endTime = System.nanoTime();
System.out.println("Arrays.copyOfRange()运行了"+(endTime-beginTime)+"ns");
System.out.println(b[n-1]);
}
public static void testFor() {
int n=10000;
int[] a= new int[n];
for(int i=0;i<n;i++) {
a[i]=i;
}
int[] b= new int[n];
long beginTime = System.nanoTime();
for(int i=0;i<a.length;i++) {
b[i]=a[i];
}
long endTime = System.nanoTime();
System.out.println("for循环运行了"+(endTime-beginTime)+"ns");
System.out.println(b[n-1]);
}
public static void main(String[] args) {
testClone();
testSystemArrayCopy();
testArraysCopyof();
testCopyOfRange();
testFor();
}
}
运行结果如下:
PS:粗浅认为是性能优劣排序为System.arraycopy>clone约等于Arrays.copyOfRange>Arrays.copyOf>for,其中Arrays.copyOfRange(PS:其实记住System.arraycopy快,for慢就差不多了)与Arrays.copyOf源码都是使用System.arraycopy(如下图所示)。
经常看到这类博客,有详细的描述也有粗浅的比较,今天心血来潮动手试试,这种感觉和看博客、记概念是不一样的,挺好。
函数的详细使用,网络资料不少,在此我就不摘抄了。