java中实现数组复制的方式主要有以下几种
1、for循环逐一复制:
该方式比较灵活,但是代码不够简洁,效率也不是很好
2、使用System类的arrayCopy()方法:
该方法使用了native修饰,也就是说这是一个原生态的方法,效率比较高
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
3、使用Arrays的copyOf方法:
查看源代码可以看到copyOf方法首先创建了一个新的数组,然后在调用System.arrayCopy方法来实现数组的复制,因此该方式显然不如直接调用System.arrayCopy方法效率高。
public static int[] copyOf(int[] original, int newLength) { int[] copy = new int[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
4、使用clone方法
通过源码可以看到该方法也是一个native方法,但其返回值为Object,因此赋值时会发生强转。其效率并不高
protected native Object clone() throws CloneNotSupportedException;
下面通过一个简单的测试来比较这几种方式的优劣
package com.rogercw; import java.util.Arrays; public class Demo { //创建两个大小为1024*1024*10的数组 int[] src=new int[1024*1024*10]; int[] dest=new int[1024*1024*10]; public static void main(String[] args) { Demo demo=new Demo(); demo.init(); demo.test1(); demo.test2(); demo.test3(); demo.test4(); } /** * 初始化原数组 */ public void init() { for(int i=0;i<src.length;i++) { src[i]=i; } } /** * 测试for循环复制 */ public void test1() { long start=System.currentTimeMillis(); for(int i=0;i<src.length;i++) { dest[i]=src[i]; } long end=System.currentTimeMillis(); System.out.println("for:"+(end-start)); } /** * 测试System.arraycopy方法 */ public void test2() { long start=System.currentTimeMillis(); System.arraycopy(src, 0, dest, 0, src.length); long end=System.currentTimeMillis(); System.out.println("arrayCopy:"+(end-start)); } /** * 测试Arrays.copyOf方法 */ public void test3() { long start=System.currentTimeMillis(); dest = Arrays.copyOf(src, src.length); long end=System.currentTimeMillis(); System.out.println("copyOf:"+(end-start)); } /** * 测试clone方法 */ public void test4() { long start=System.currentTimeMillis(); dest=src.clone(); long end=System.currentTimeMillis(); System.out.println("clone:"+(end-start)); } }
打印的结果如下:
for:31
arrayCopy:16
copyOf:52
clone:63
通过修改数组的大小并多次测试,可以发现前两种方式明显优于后面两种方式,而for循环与System.cooyOf方法相差并不大。
浙公网安备 33010602011771号