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
posted @ 2019-03-07 09:12  已不再畏惧  阅读(1710)  评论(0编辑  收藏  举报