Go

Do Go maps shrink after deleting entries? How do you reclaim memory?

Question 64HardGo 1.22 to 1.25

No. delete marks slots as empty (or as tombstones in Swiss tables), but the bucket or group memory is never given back. A map that once held 1M entries keeps its peak-sized table even after len(m) drops to 10. This is true for both the classic and the Swiss-table implementations. A frequent production example is a session cache that spikes during a traffic burst and never shrinks again.

// Reclaim by rebuilding into a right-sized map
func shrink[K comparable, V any](m map[K]V) map[K]V {
	n := make(map[K]V, len(m))
	maps.Copy(n, m)
	return n // old map becomes garbage once unreferenced
}

cache = shrink(cache) // e.g. periodically, or when len drops far below peak

// clear(m) removes all entries but generally keeps the allocated table for reuse.
// To actually release memory: m = make(map[K]V) (or nil) and drop the old reference.

Mitigations:

  • Rebuild periodically.
  • Store pointers (map[K]*V) so that large values can be freed even though slots remain. The slots still cost pointer-sized memory.
  • Shard the cache and rotate the shards.
  • Use a bounded LRU cache.

What the interviewer wants: you can diagnose "memory never goes down" from a heap profile, and you understand that the runtime favours cheap deletes, and avoids rehash churn when a map shrinks and regrows, over giving memory back.

More on Arrays, Slices, Maps & Strings

All 37 Arrays, Slices, Maps & Strings questions