对数组arraycopy、clone和普通的循环赋值的性能分析

下面是测试的代码:
public class ArrayCopyPerformanceTest {

	public static class Person {
        public String name;
    }
    public static void main(String[] args) {
        int arraySize = 1000;
        int testTimes = 100000;
 
        Person[] ps1 = genPersons(arraySize);
 
        long t1 = System.currentTimeMillis();
        Person[] ps2 = new Person[arraySize];
        for (int i = 0; i < testTimes; i++) {
            System.arraycopy(ps1, 0, ps2, 0, arraySize);
        }
        long t2 = System.currentTimeMillis();
        System.out.println("time used by System.arraycopy: " + (t2 - t1) + "ms");

        long t = System.currentTimeMillis();
        Person[] ps = new Person[arraySize];
        for (int i = 0; i < testTimes; i++) {
        	ps2 = ps1.clone();
        }
        long tt = System.currentTimeMillis();
        System.out.println("time used by clone: " + (tt - t) + "ms");
 
        t1 = System.currentTimeMillis();
        ps2 = new Person[arraySize];
        for (int i = 0; i < testTimes; i++) {
            for (int j = 0; j < arraySize; j++) {
                ps2[j] = ps1[j];
            }
        }
        t2 = System.currentTimeMillis();
        System.out.println("time used by manual loop: " + (t2 - t1) + "ms");
    }
 
    public static Person[] genPersons(int arraySize) {
        Person[] ps = new Person[arraySize];
        for (int i = 0; i < arraySize; i++) {
            Person p = new Person();
            p.name = "james" + i;
            ps[i] = p;
        }
 
        return ps;
    }

}

执行的结果:

time used by System.arraycopy: 116ms
time used by clone: 370ms
time used by manual loop: 641ms

从结果来看性能还是会有不小的差距的,clone虽然在性能上较之普通循环赋值有所提升,但是,不够灵活,不能指定赋值的元素,而且,java内置的集合类型,eg,ArrayList,内部的add()和remove()方法的内部实现都是用arraycopy的。所以,综合来说,对于批量数据的赋值推荐用arraycopy。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值