没有合适的资源?快使用搜索试试~ 我知道了~
在Java语言中,一般会采用下面的几种方法进行数组的复制。 a) for循环逐一复制; b) System.arraycopy()方法 c) Arrays.copyOf()方法 d) 使用clone()方法 e) Arrays.copyOfRange()方法 接下来,我们看下这几种方法的效率和源码,以及如何使用序列化和反序列化实现组合类的深复制。 我们以百万级和千万级的数据作为测试集。测试源码如下: public static void main(String[] args) throws CloneNotSupportedException { // int length = 1000
资源推荐
资源详情
资源评论
实现数组复制常用的实现数组复制常用的5种方式及组合类的深复制种方式及组合类的深复制(深拷贝深拷贝)
在Java语言中,一般会采用下面的几种方法进行数组的复制。
a) for循环逐一复制;
b) System.arraycopy()方法
c) Arrays.copyOf()方法
d) 使用clone()方法
e) Arrays.copyOfRange()方法
接下来,我们看下这几种方法的效率和源码,以及如何使用序列化和反序列化实现组合类的深复制。接下来,我们看下这几种方法的效率和源码,以及如何使用序列化和反序列化实现组合类的深复制。
我们以百万级和千万级的数据作为测试集。测试源码如下:
public static void main(String[] args) throws CloneNotSupportedException {
// int length = 10000000; // 千万级别
int length = 5000000; // 百万级别
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() 循环方法
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");
// System.arraycopy() 方法
start = System.currentTimeMillis();
System.arraycopy(arr, 0, arr2, 0, length);
end = System.currentTimeMillis();
System.out.println("System.arraycopy()方法耗费时间:" + (end - start) + "ms");
// Arrays.copyOf() 方法
start = System.currentTimeMillis();
arr2 = Arrays.copyOf(arr, length);
end = System.currentTimeMillis();
System.out.println("Arrays.copyOf()方法耗费时间:" + (end - start) + "ms");
// Object.clone() 方法, 数组默认实现了Cloneable接口
start = System.currentTimeMillis();
arr2 = arr.clone();
end = System.currentTimeMillis();
System.out.println("Object.clone()方法耗费时间:" + (end - start) + "ms");
// Arrays.copyOfRange() 方法
start = System.currentTimeMillis();
arr2 = Arrays.copyOfRange(arr, 0, length);
end = System.currentTimeMillis();
System.out.println("Arrays.copyOfRange()方法耗费时间:" + (end - start) + "ms");
}
百万级测试结果:
for()循环方法耗费时间:11ms
System.arraycopy()方法耗费时间:6ms
Arrays.copyOf()方法耗费时间:9ms
Object.clone()方法耗费时间:8ms
Arrays.copyOfRange()方法耗费时间:8ms
千万级测试结果:
for()循环方法耗费时间:20ms
System.arraycopy()方法耗费时间:13ms
Arrays.copyOf()方法耗费时间:16ms
Object.clone()方法耗费时间:15ms
Arrays.copyOfRange()方法耗费时间:16ms
资源评论
weixin_38632006
- 粉丝: 3
- 资源: 939
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功