Java中数组复制的四种方法
来源:互联网 发布:闪光灯软件哪个好 编辑:程序博客网 时间:2024/06/05 03:36
数组复制的方法
- 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"); }}
数据量是百万级别的情况下:
数据量是千万级别的情况下:
阅读全文
0 0
- Java中数组复制的四种方法
- java复制数组的四种方法
- C#中数组复制的四种方法
- java语言复制数组的四种方法
- java语言复制数组的四种方法
- java语言复制数组的四种方法
- java语言复制数组的四种方法
- 数组的四种复制方法
- java中复制数组的方法
- java中复制数组的方法
- JAVA中复制数组的方法
- Java中数组复制的2种方法
- JAVA中复制数组的五种方法
- Java中数组复制的几种方法
- Java中数组复制的几种方法
- JAVA中数组复制的几种方法
- Java中数组复制的几种方法
- JAVA中复制数组的五种方法
- 第十三章:事件(内存和性能、模拟事件)
- show processlist命令
- 【电子产品】ThinkPad S5 Intel(R) Dual Band Wireless-AC 3165 网卡驱动莫名其妙挂掉
- 10年跳槽经验总结 高级人才不用找工作
- Strust2学习之Struts运行原理
- Java中数组复制的四种方法
- 杂谈 | 关于二维码
- Android开发之常用的第三方框架
- Leetcode算法题目:Rotate Image
- intellij Idea热部署失效问题解决方案
- Restful接口实现方法
- WebService开发方法介绍
- 数字分隔(二)
- 创建一个定时作业进行数据库备份