最近項目裏發現構造方法和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倍左右