Golang / Golang Internals and Memory Management Interview Questions
How are Go maps implemented internally and what does that mean for performance?
Go's built-in map is a hash table composed of an array of buckets. Each bucket holds up to 8 key-value pairs and a compact bitmask (the tophash) of the top 8 bits of each key's hash — used for quick equality rejection without a full key comparison.
// Map creation
m := make(map[string]int) // empty, grows as needed
m2 := make(map[string]int, 100) // hint: pre-allocate for ~100 entries
// The hint avoids rehashing during initial population
// Map automatically grows (rehash) when load factor ~6.5 entries/bucket
// Comma-ok idiom — distinguish missing key from zero value
m["alice"] = 0
val, ok := m["alice"] // val=0, ok=true — key exists
val, ok = m["bob"] // val=0, ok=false — key absent
if !ok { fmt.Println("key not found") }
// Deleting a key
delete(m, "alice") // no-op if key absent, no panic
// Iteration order is intentionally randomised
for k, v := range m {
fmt.Println(k, v) // order differs across runs
}
// Maps are NOT thread-safe — concurrent reads+writes cause a fatal error
// Detected by the race detector: go run -race ./...
// Safe alternatives:
// 1. sync.Mutex protecting the map
// 2. sync.RWMutex for read-heavy workloads
// 3. sync.Map (optimised for high-concurrency, low-write scenarios)| Concept | Detail |
|---|---|
| Bucket size | 8 key-value pairs per bucket |
| Tophash | Top 8 bits of hash stored per slot for fast rejection |
| Load factor | Rehash triggered at ~6.5 entries/bucket (overflow buckets used before) |
| Iteration order | Randomised per run — the runtime deliberately adds randomisation |
| Thread safety | Not thread-safe — use sync.Mutex, sync.RWMutex, or sync.Map |
| Key requirement | Keys must be comparable (==); slices, maps, functions cannot be keys |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
