hakunami
hakunami

Reputation: 2441

Does Guava ImmutableMap postpone Map resize?

While I am testing the Guava ImmutableMap and HashMap, I found ImmutableMap resize not at regular point, aka, 16, 32, 64. What does this mean?

Test code:

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));
}

Result graph: enter image description here

Y-axis is memory footprint in bytes, and X-axis is map size. Blue is HashMap and Orange is ImmutableMap. You can see ImmutableMap resize later than HashMap.

Upvotes: 4

Views: 202

Answers (1)

user158037
user158037

Reputation: 2603

It is just a different load factor - 1.33 for normal HashMap and 1.2 for ImmutableMap. All hash maps have free space as hashing is never perfect, mutable maps need additional space for potential new entries. Look at Guava com.google.common.collect.Hashing.closedTableSize(), Guava com.google.common.collect.RegularImmutableMap.MAX_LOAD_FACTOR, and java.util.HashMap.DEFAULT_LOAD_FACTOR.

Upvotes: 4

Related Questions