1. 程式人生 > >java 迴圈巢狀組裝資料效能和調整方法

java 迴圈巢狀組裝資料效能和調整方法

先直接上測試程式碼

public static void main(String[] args){
    List<DealerInfoOut> list = new ArrayList<>();
    List<DealerInfoOut> otherList = new ArrayList<>();
    for(int i=0 ; i<=10000;i++){
        DealerInfoOut infoOut = new DealerInfoOut();
        DealerInfoOut otherInfoOut = new 
DealerInfoOut(); infoOut.setDealerId(i); otherInfoOut.setDealerId(10000-i); otherInfoOut.setDealerSimpleName((10000-i)+""); list.add(infoOut); otherList.add(otherInfoOut); } // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.ms");// 其中 //處理方式1 System.out
.println("start1="+sdf.format(new Date())); Map<Integer,DealerInfoOut> map = new HashMap<>(); for(DealerInfoOut otherInfoOut:otherList){ map.put(otherInfoOut.getDealerId(),otherInfoOut); } for(DealerInfoOut infoOut:list){ if(map.containsKey(infoOut.getDealerId())){ infoOut.setDealerSimpleName(map.get(infoOut.getDealerId()).getDealerSimpleName()); } } System.out
.println("end1="+sdf.format(new Date())); //處理方式2 System.out.println("start2="+sdf.format(new Date())); for(DealerInfoOut infoOut:list){ for(DealerInfoOut otherInfoOut:otherList){ if(infoOut.getDealerId().equals(otherInfoOut.getDealerId())){ infoOut.setDealerSimpleName(otherInfoOut.getDealerSimpleName()); break; } } } System.out.println("end2="+sdf.format(new Date())); } 通過輸出的時間可以看到方式1所用時間基本不超過1毫秒,方式2在有1萬資料的時候所用時間大概在1秒左右.當資料量為10萬時,方式2我大概等了10幾秒都沒處理完.