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

猜你喜欢

转载自www.cnblogs.com/Absorbed/p/10487422.html