Guava ImmutableMap 会推迟 Map 调整大小吗?

Does Guava ImmutableMap postpone Map resize?

当我在测试 Guava ImmutableMap 和 HashMap 时,我发现 ImmutableMap 调整大小不在常规点,也就是 16、32、64。这是什么意思?

测试代码:

Map<Integer, Integer> mapFootPrint = new HashMap<Integer, Integer>();

for(int i = 1; i < 1000; i ++){
    mapFootPrint.put(i, i+ 128); //no cache integer
    ImmutableMap<Integer, Integer> immutableMap = ImmutableMap.copyOf(mapFootPrint);

    System.out.println(MemoryMeasurer.measureBytes(mapFootPrint));
    System.out.println(MemoryMeasurer.measureBytes(immutableMap));
}

结果图:

Y 轴是以字节为单位的内存占用,X 轴是地图大小。蓝色是 HashMap,橙色是 ImmutableMap。你可以看到 ImmutableMap 调整大小比 HashMap 晚。

这只是一个不同的负载系数 - 正常 HashMap 为 1.33,ImmutableMap 为 1.2。所有哈希映射都有免费的 space,因为哈希从来都不是完美的,可变映射需要额外的 space 用于潜在的新条目。看看 Guava com.google.common.collect.Hashing.closedTableSize()、Guava com.google.common.collect.RegularImmutableMap.MAX_LOAD_FACTORjava.util.HashMap.DEFAULT_LOAD_FACTOR.