最近项目里发现构造方法和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倍左右