java数组拷贝哪个效率高

之前看到很多问题以及很多博客都有讨论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(如下图所示)。

经常看到这类博客,有详细的描述也有粗浅的比较,今天心血来潮动手试试,这种感觉和看博客、记概念是不一样的,挺好。

函数的详细使用,网络资料不少,在此我就不摘抄了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值