大量for循环中new对象与clone效率对比

  • 创建实体类,实现Cloneable接口,重写被保护的Object的clone()方法

import lombok.Data;

/**
 *@author liuxingying
 *@description
 *@since 2020/12/30
 */
@Data
public class User implements Cloneable{

    private Integer age;
    private String name;

    @Override
    public User clone() throws CloneNotSupportedException {
        return (User) super.clone();
    }
}

  • 实现对比
 public static void main(String[] args) {
        List<User> userList1 = new ArrayList<>();
        List<User> userList2 = new ArrayList<>();

        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            User u1 = new User();
            u1.setAge(10);
            u1.setName("Tom" + i);
            userList1.add(u1);
        }
        long t2 = System.currentTimeMillis();


        User u1 = new User();
        try {
            for (int i = 0; i < 1000000; i++) {
                User u2 = u1.clone();//每次clone后是创建新的对象
                u2.setAge(20);
                u2.setName("Tom" + i);
                userList2.add(u2);
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        long t3 = System.currentTimeMillis();

        System.out.println(t2 - t1);
        System.out.println(t3 - t2);
    }
  • 结果
106
59
  • 在数据了大的情况下,如果在循环内直接new对象,效率会非常低下,可以采用原型模式,先new出一个对象来,后面全部通过clone操作进行,也就是浅拷贝,效率会大幅提升。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值