java数组的四种拷贝方法的性能分析:for、clone、System.arraycopy、Arrays.copyof

xiaoxiao2021-02-28  91

今天作者就Java数组的拷贝方法进行性能比较,多有不足,请大家指正!!! 1.for方法,用循环依次实现数组元素的拷贝。 2.clone方法,是Object类的方法,用来实现对象的复制操作。 3.System.arraycopyof方法,是System的静态方法,是一个native方法,用来实现数组的复制操作,提供了多种重载方法,大家可以去看源码了解了解。 4.Arrays.copyof方法,是Arrays工具类的静态方法,其底层调用System.arraycopy方法,也提供了多种重载方法,用来实现数组的复制操作。 源码分析: package JavaNukeTest; import java.util.Arrays; public class ArrayCopyTest { public static final int size = 10000; public static void copyByClone(String[] strArray){ long startTime = System.nanoTime(); String[] destArray = strArray.clone(); long endTime = System.nanoTime(); System.out.println("copyByClone cost time is "+(endTime - startTime)); } public static void copyByLoop(String[] strArray){ long startTime = System.nanoTime(); String[] destArray = new String[size]; for (int i = 0; i < strArray.length; i++){ destArray[i] = strArray[i]; } long endTime = System.nanoTime(); System.out.println("copyByLoop cost time is "+(endTime - startTime)); } public static void copyByArrayCopy(String[] strArray){ long startTime = System.nanoTime(); String[] destArray = new String[size]; System.arraycopy(strArray, 0, destArray, 0, strArray.length); long endTime = System.nanoTime(); System.out.println("copyByArrayCopy cost time is "+(endTime - startTime)); } public static void copyByCopyof(String[] strArray){ long startTime = System.nanoTime(); String[] destArray = Arrays.copyOf(strArray, strArray.length); long endTime = System.nanoTime(); System.out.println("copyByCopyof cost time is "+(endTime - startTime)); } public static void main(String[] args) { // TODO Auto-generated method stub String[] strArray = new String[size]; for (int i = 0; i < size; i++){ strArray[i] = "abc"; } copyByClone(strArray); copyByLoop(strArray); copyByArrayCopy(strArray); copyByCopyof(strArray); } } 运行结果: 当我把size改为10时,运行结果如下: 当我把size改为100时,运行结果如下: 当我把size改为1000时,运行结果如下: 也就是说,当数组元素个数不是很大时,使用for来复制数组,时间性能是最好的,clone次之,其次是System.arraycopy,最差的是Arrays.copyof。 当数组元素个数很大时,使用System.arraycopy复制数组,时间性能是最好的,clone次之,其次是Arrays.copyof,最差的就是for。
转载请注明原文地址: https://www.6miu.com/read-64391.html

最新回复(0)