Java : Iteration through a HashMap, 哪个效率更高?

标签 java map performance hashmap iteration

给定以下代码,有两种替代方法可以遍历它,
这两种方法在性能上有区别吗?

        Map<String, Integer> map = new HashMap<String, Integer>();
        //populate map

        //alt. #1
        for (String key : map.keySet())
        {
            Integer value = map.get(key);
            //use key and value
        }

        //alt. #2
        for (Map.Entry<String, Integer> entry : map.entrySet())
        {
            String key = entry.getKey();
            Integer value = entry.getValue();
            //use key and value
        }

我倾向于认为 alt. #2 是遍历整个 map 的更有效方法(但我可能错了)

最佳答案

您的第二个选项肯定更有效,因为与第一个选项中的 n 次相比,您只进行一次查找。

但是,没有什么比尽可能尝试更好的了。所以这里 -

(不完美,但足以验证假设并在我的机器上)

public static void main(String args[]) {

    Map<String, Integer> map = new HashMap<String, Integer>();
    // populate map

    int mapSize = 500000;
    int strLength = 5;
    for(int i=0;i<mapSize;i++)
        map.put(RandomStringUtils.random(strLength), RandomUtils.nextInt());
    
    long start = System.currentTimeMillis();
    // alt. #1
    for (String key : map.keySet()) {
        Integer value = map.get(key);
        // use key and value
    }
    System.out.println("Alt #1 took "+(System.currentTimeMillis()-start)+" ms");
    
    start = System.currentTimeMillis();
    // alt. #2
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        String key = entry.getKey();
        Integer value = entry.getValue();
        // use key and value
    }
    System.out.println("Alt #2 took "+(System.currentTimeMillis()-start)+" ms");
}

结果(一些有趣的)

使用 int mapSize = 5000; int strLength = 5;
Alt #1 耗时 26 毫秒
Alt #2 耗时 20 毫秒

使用 int mapSize = 50000; int strLength = 5;
Alt #1 耗时 32 毫秒
Alt #2 耗时 20 毫秒

使用 int mapSize = 50000; int strLength = 50;
Alt #1 耗时 22 毫秒
Alt #2 耗时 21 毫秒

使用 int mapSize = 50000; int strLength = 500;
Alt #1 耗时 28 毫秒
Alt #2 耗时 23 毫秒

使用 int mapSize = 500000; int strLength = 5;
Alt #1 耗时 92 毫秒
Alt #2 耗时 57 毫秒

...等等

关于Java : Iteration through a HashMap, 哪个效率更高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5826384/

相关文章:

java - 向 SQLite Table Android 添加数百个条目

java - Android 中是否有某种#define 可用于简化语句?

android - ItemizedOverlay 的 setFocus(overlayItem) 不起作用

map - map 阶段结束后停止Hadoop

grails - 如何使用Grails在数据库中保存类别和相关子类别

javascript - 更干净更快的 JavaScript,用 JavaScript 替换 jQuery

c++ - 使用 AVX 内在函数而不是 SSE 并不能提高速度——为什么?

java - 第一次从 Java 调用 MS Access 的 SQL 命令非常慢,但后续运行时速度会快得多

java - 如何发现 List<Integer> 中缺少的渐进算术数在 Java 8 中是什么?

java - 用于国际化 i18n 测试的 Eclipse 插件