map 幾種遍歷性能比較


public class MyDemo001 {
    private static final Logger log = LoggerFactory.getLogger(MyDemo001.class);
    public static void main(String[] args) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i =0;i<100000;i++){
            map.put(i,i);
        }

        long end = System.currentTimeMillis();
        map.entrySet().forEach(endrt->{
            new String();
        });
        long start = System.currentTimeMillis();
        log.info("entrySet.forEach :::::>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:"+(start-end));

        for(Integer s:map.keySet()){
//            System.out.println("key : "+s+" value : "+map.get(s));
            new String();
        }
        end = System.currentTimeMillis();
        log.info("map.keySet()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:"+(end-start));
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
//            System.out.println("鍵 key :"+entry.getKey()+" 值value :"+entry.getValue());
            new String();
        }
        start = System.currentTimeMillis();
        log.info("Map.Entry()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:"+(start-end));


        Iterator<Map.Entry<Integer, Integer>> it=map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<Integer, Integer> entry=it.next();
//            System.out.println("鍵key :"+entry.getKey()+" value :"+entry.getValue());
            new String();
            }
        end = System.currentTimeMillis();
        log.info("Iterator  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:"+(end-start));
    }


}

結果輸出:

[INFO] entrySet.forEach :::::>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:48
[INFO] map.keySet()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:6
[INFO] Map.Entry()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:4
[INFO] Iterator  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:2

綜合:

Iterator>Map.Entry()>map.keySet()>entrySet.forEach


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM