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 |
More Related questions...