Java遍历Map Key-Value的几种方式的效率对比

    public static void main(String[] args) {
        traverseMap();
    }


    public static void traverseMap() {
        long start = 0;
        long finish = 0;
        long sum = 0;

        Map map = createTestMap();
        start = System.currentTimeMillis();
        Set> entrySet = map.entrySet();
        for (Map.Entry entry : entrySet){
            sum += entry.getValue();
        }
        finish = System.currentTimeMillis();
        System.out.println("entrySet | sum:" + sum + ", cost:" + (finish - start) + "ms");

        sum = 0;
        start = System.currentTimeMillis();
        Set keySet = map.keySet();
        for (String key : keySet){
            sum += map.get(key);
        }
        finish = System.currentTimeMillis();
        System.out.println("keySet | sum:" + sum + ", cost:" + (finish - start) + "ms");

        sum = 0;
        start = System.currentTimeMillis();
        Iterator itr = map.entrySet().iterator();
        Map.Entry entry = null;
        while (itr.hasNext()) {
            entry = (Map.Entry) itr.next();
            sum += (Integer) entry.getValue();
        }
        finish = System.currentTimeMillis();
        System.out.println("iterator | sum:" + sum + ", cost:" + (finish - start) + "ms");
    }

    private static Map createTestMap() {
        Map map = new HashMap<>();
        for (int i = 0; i < 10000000; i++) {
            map.put(Integer.toString(i), i);
        }
        return map;
    }

从实测结果看,大多情况下使用entrySet迭代器是最快的,直接遍历entrySet次之,但相差非常小,遍历keySet再通过key找value是最慢的,其实很容易理解:通过key去Map里取value需要经过hash的计算,和Hash表的查询,这之间必然会消耗性能,特别是如果key的hashCode方法又实现不好或者较复杂的话,情况会更糟糕。

其中某一次的测试输出:

entrySet | sum:49999995000000, cost:238ms
keySet | sum:49999995000000, cost:361ms
iterator | sum:49999995000000, cost:232ms

你可能感兴趣的:(Java)