HashMap遍历性能

一,说明

实际生产中遍历Map是一件很常见的事情,现在看看性能如何

二,代码

1,遍历有如下几种方法

public void testPerformance () {
        int size = 5000000;
        HashMap<Object, Object> hashMap = new HashMap<>(size);
        for (int i = 0; i < size; i++) {
            hashMap.put(i, "demo" + i);
        }

//        1,方法1
        Stopwatch stopwatch1 = Stopwatch.createStarted();
        Set set = hashMap.keySet();
        for (Object obj : set) {
            hashMap.get(obj);
        }
        System.out.println();
        System.out.println(stopwatch1);

//        2,方法2
        Stopwatch stopwatch2 = Stopwatch.createStarted();
        Iterator<Map.Entry<Object, Object>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Object, Object> entry = iterator.next();
            entry.getKey();entry.getValue();
        }
        System.out.println();
        System.out.println(stopwatch2);

//        3,方法3
        Stopwatch stopwatch3 = Stopwatch.createStarted();
        for (Map.Entry<Object, Object> entry : hashMap.entrySet()) {
            entry.getKey() ; entry.getValue();
        }
        System.out.println();
        System.out.println(stopwatch3);


    }

2,性能表现

 

 

 

3,说明

代码中用的Stopwatch是谷歌的工具类

pom这样引入

     <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>

 

4,分析

迭代器和foreach对于entryset方法性能差不多,都是逐一遍历,keyset方法之所以性能较低主要由于keyset完了以后要去调用get方法,导致多一步资源浪费。

posted @ 2021-02-03 22:16  superChong  阅读(132)  评论(0编辑  收藏  举报