How would you choose the correct initial capacity for a HashMap to avoid unnecessary resizing overhead, given the relationship between capacity, load factor, and resize threshold?
Short answer
HashMap resizes (doubling its internal bucket array and rehashing every entry, an O(n) operation) once the number of entries exceeds capacity * loadFactor (default load factor 0.75) -- if you know approximately how many entries a map will ultimately hold, pre-sizing its initial…
Advertisement
AModel answer
HashMap resizes (doubling its internal bucket array and rehashing every entry, an O(n) operation) once the number of entries exceeds capacity * loadFactor (default load factor 0.75) -- if you know approximately how many entries a map will ultimately hold, pre-sizing its initial capacity to avoid multiple resize operations during population can meaningfully improve performance for large maps built in a tight loop, calculated as roughly expectedSize / loadFactor, rounded up to the next power of two (since HashMap always uses power-of-two capacities internally regardless of what you request).
// Without pre-sizing: multiple resizes occur as the map grows past each threshold
Map<String, Integer> map1 = new HashMap<>(); // default capacity 16
for (int i = 0; i < 10_000; i++) map1.put("key" + i, i); // resizes many times along the way
// Pre-sized to avoid resizing: capacity chosen to comfortably hold 10,000 entries at 0.75 load factor
Map<String, Integer> map2 = new HashMap<>(14000); // ~10000 / 0.75, rounded up internally to a power of 2Real-world example
A batch data-loading process building a HashMap from a known-size dataset of 500,000 records pre-sizes the HashMap's initial capacity based on that known count, measurably reducing load time by avoiding the dozen-plus incremental resize-and-rehash operations that would otherwise occur as the default-sized map grows.
Likely follow-ups
- Why does HashMap always round the requested capacity up to the next power of two internally?
- What's the memory trade-off of over-provisioning initial capacity versus the performance cost of resizing?
Related topics