【问题标题】:Does Guava ImmutableMap postpone Map resize?Guava ImmutableMap 会推迟地图调整大小吗?
【发布时间】:2016-01-07 11:31:57
【问题描述】:

在测试 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 晚。

【问题讨论】:

    标签: java hashmap guava


    【解决方案1】:

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

    【讨论】:

    • 似乎是负载系数问题。但我使用的是 Java 7 HotSpot 64 位,DEFAULT_LOAD_FACTOR 是 0.75f。您知道为什么 Google 会选择不同的比率吗?任何基准?
    • 数字的存储和应用方式有所不同——一个库使用乘法,另一个使用除法:items*1.33 = items/(0.75), items*1.25 = items/(0.80)
    猜你喜欢
    • 2012-03-18
    • 2014-03-22
    • 2010-12-21
    • 2015-01-25
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多