有人知道 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/