java 构造方法和set赋值哪个快?

最近项目里发现构造方法和set复制的代码比较多,但是这两种在效率上有什么区别呢?
让我们来手动实测一下,首先贴上测试代码:

首先上两个实体类,属性都是相同的,这里使用了 lombok 插件

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDto {

    private String username;

    private String password;

    private String password1;

    private String password2;

    private String password3;


    private String password4;

    private String password5;

    private String password6;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDto1 {

    private String username;

    private String password;

    private String password1;

    private String password2;

    private String password3;


    private String password4;

    private String password5;

    private String password6;
}

我们写好实体类现在开始测试吧

public class Test {
    public static void main(String[] args) throws Exception{

        new Thread(()->{
            List<UserDto> userDtoList = new ArrayList<>();
            long startTime=System.nanoTime()  /1000000L;   //获取开始时间
            for(int i=0 ;i<10000;i++){
                userDtoList.add(new UserDto("test"+i,"123456","123456","123456","123456","123456","123456","123456"));
            }
            long endTime=System.nanoTime()  /1000000L; //获取结束时间
            System.out.println(Thread.currentThread().getName() +":构造-》程序运行时间: "+(endTime-startTime)+"ms");
        }).start();

        new Thread(()->{
            List<UserDto1> userDtoList1= new ArrayList<>();
            long startTime1=System.nanoTime()  /1000000L;   //获取开始时间
            for(int i=0 ;i<10000;i++){
                userDtoList1.add(new UserDto1());
                userDtoList1.get( i ).setUsername("test"+i  );
                userDtoList1.get( i ).setPassword( "123456" );
                userDtoList1.get( i ).setPassword1( "123456" );
                userDtoList1.get( i ).setPassword2( "123456" );
                userDtoList1.get( i ).setPassword3( "123456" );
                userDtoList1.get( i ).setPassword4( "123456" );
                userDtoList1.get( i ).setPassword5( "123456" );
                userDtoList1.get( i ).setPassword6( "123456" );
            }
            long endTime1=System.nanoTime()  /1000000L; //获取结束时间
            System.out.println(Thread.currentThread().getName() +":set-》程序运行时间: "+(endTime1-startTime1)+"ms");
        }).start();
    }
}

这里我们创建两个线程,分别创建了1W个对象加入在数组里面,考虑到内存地址问题,分别使用了UserDto、UserDto1对象

输出结果如下:

Thread-0:构造-》程序运行时间: 8ms
Thread-1:set-》程序运行时间: 15ms

结论

可见,对象在构造复制和set复制,速度上差距2倍左右

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值