java - ConcurrentHashMap 内存开销

标签 java hashmap concurrenthashmap memory-profiling

有人知道 ConcurrentHashMap 的内存开销是多少(与“经典”HashMap 相比)吗?

  • 在 build 中?
  • 在插入元素时?

最佳答案

如果您在 64 位 JVM 上使用 -XX:-UseTLAB -XX:NewSize=900m -mx1g 运行以下命令。

public static void main(String... args) throws NoSuchMethodException, IllegalAccessException {
    for (int i = 0; i < 4; i++) {
        long used1 = usedMemory();
        populate(new HashMap());
        long used2 = usedMemory();
        populate(new ConcurrentHashMap());
        long used3 = usedMemory();
        System.out.println("The ratio of used memory is " + (double) (used3 - used2) / (used2 - used1));
        System.out.println("For an extra " + ((used3 - used2) - (used2 - used1)) / 1000000 + " bytes per entry was used.");
    }
}

private static void populate(Map map) {
    for (Integer i = 0; i < 1000000; i++)
        map.put(i, i);
}

private static long usedMemory() {
    return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}

您获得 Java 6 和 7 的一百万个条目。

The ratio of used memory is 1.1291128466982379
For an extra 8 bytes per entry was used.
The ratio of used memory is 1.1292086928728067
For an extra 8 bytes per entry was used.
The ratio of used memory is 1.1292086928728067
For an extra 8 bytes per entry was used.
The ratio of used memory is 1.1292086928728067
For an extra 8 bytes per entry was used.

8 MB 内存的成本约为 5 美分。

关于java - ConcurrentHashMap 内存开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11103216/

相关文章:

java - 解决HashMap哈希冲突的技术是否可配置

java - 我应该使用 ConcurrentHashMap 吗?

java - 为 ConcurrentHashMap 初始化值的最快方法

java - Hashtable over ConcurrentHashMap 的具体用法

java - 适用于多种数据类型的 RecyclerView.Adapter

java - 与 Java Swing 定时器混淆

java - 我们需要运行多少次 Java 程序来预热 JVM?

java - 为单独的对象设置动画

Java:如何使用 HashMap 根据第二列中的条件对一列的所有值求和

Java Hash Multi Map(键多值)实现