java - 少量条目的 Java Map 最快实现

标签 java performance collections map

java.util.Map 最快的实现是什么?对于极少数条目(少于 15 个元素左右)?线程安全和非线程安全。

最佳答案

如果所有条目都可以表示为枚举,请使用 EnumMap :

This implementation combines the richness and safety of the Map interface with a speed approaching that of an array. If you want to map an enum to a value, you should always use an EnumMap in preference to an array.

如果没有,HashMap是很好的解决方案。它为基本操作提供恒定时间,例如 get()put():

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.

请记住在您的 HashMap 中设置较低的 capacity 值:

Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

当然,上面的实现不是线程安全的。在这种情况下最好的线程安全实现将是 ConcurrentHashMap .它结合了 HashMap 的高性能和线程安全性。

Here is不同 Map 实现的良好比较。

编辑:Here is不同 HashMap 实现的有趣比较。看起来,至少对于基本类型,有比内置 HashMap 更快的替代方案。

Edit2:由于 Peter Lawrey 的回答,我决定进行一些测试,比较 ConcurrentHashMapCollections.synchronizedMap() :

public static void main(String[] args) {
      System.out.println("\n===== ConcurrentHashMap =====");
      testMap(new ConcurrentHashMap<>());
      System.out.println("\n===== Collections.synchronizedMap()  =====");
      testMap(Collections.synchronizedMap(new HashMap<>()));
}

    static final int N = 5;
    static final int R = 1000000;

    public static void testMap(Map map) {
        long startTime = System.nanoTime();

        System.out.println("\n-- " + N*R + " puts(key, value) --");
        startTime = System.nanoTime();
        for (int j = 0; j < R; j++) {
            for (int i = 0; i < N; i++) 
                map.put(i, new float[] { 0f, 1f, 2f, 3f, 4f });
            map.clear();
        }
        System.out.println((System.nanoTime() - startTime) / 1000000000.0);

        System.out.println("\n-- " + N*R + " get(key) --");
        startTime = System.nanoTime();
        for (int j = 0; j < R; j++) {
            for (int i = 0; i < N; i++)  
                map.get(i); 
            map.clear();
        }
        System.out.println((System.nanoTime() - startTime) / 1000000000.0);
    }

}

我的结果是:

===== ConcurrentHashMap =====

  • 5000000 次放置(键,值)- 0.99714195 秒

  • 5000000 次获取( key )- 0.452227427 秒

===== Collections.synchronizedMap() =====

  • 5000000 次放置(键,值)- 0.586431367 秒

  • 5000000 次获取( key )- 0.376051088 秒

因此,Peter 可能是对的 - 对于小 map ,Collections.synchronizedMap() 更快。

关于java - 少量条目的 Java Map 最快实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25001992/

相关文章:

collections - Mongodb 自动写入上限集合

c# - 如何在编译时驱动 C#、C++ 或 Java 编译器计算 1+2+3+...+1000?

java - post-spring mvc 之后在内部重新发布表单

java - 在向 azure-cosmosdb 发起查询时,有什么方法可以在 Java JPA (DocumentDbRepository) 中编写自定义或 native 查询吗?

java - MongoDB Java 驱动程序比带有 $gte/$lte 的控制台慢得多

mysql order by 性能优化

java - 转储不适用于 pigrunner

c# - 正则表达式操作成本

java - 编写一个程序来查找整数数组中最长连续序列的长度?

c++ - C++ 中 vector<double> 的 ArgMin?