Go to content
Web development

How Go Maps Work Under the Hood

When you write m := make(map[string]int) in Go, the runtime creates a hash table, not a simple list of pairs. A hash table stores entries in buckets, and it uses a hash function to decide which bucket should hold a given key. That design gives maps their near-constant-time lookups, but it also creates the behaviors that surprise developers: iteration order is random, the map keeps its memory after you delete everything, and concurrent writes can crash the program.

Understanding the structure explains those behaviors and helps you turn them into practical decisions. You will see how the hash table works, what the runtime does on each operation, and which choices follow: how to size a map, which key types are cheapest, when to use sync.Map, and what the experimental Swiss Table implementation changes.

A bucket is a fixed-size group of slots that stores key-value pairs. A hash function turns a key into a number; the runtime uses part of that number to pick a bucket, then compares the stored key against the lookup key to confirm a match. Collisions happen when two different keys land in the same bucket.

A map is a hash table made of buckets

The runtime represents every map with a header struct called hmap. The struct’s fields control the structure: B is the base-2 logarithm of the number of buckets, and hash0 is a random seed generated per map. buckets is the array of buckets, and oldbuckets is the previous bucket array used during growth. The arpalert analysis of the map implementation documents these fields and the migration system they support.

When you insert or look up a key, the runtime hashes the key, uses part of the hash to select a bucket. It then searches the slots in that bucket. If two keys land in the same bucket, the runtime stores both in that bucket’s slots and chains additional overflow buckets when the bucket fills up. Understanding Go’s map implementation covers this collision handling in detail.

The hash function is specialized. For string keys, the runtime uses AES encryption instructions (aeshashbody) on CPUs that support them, which produces well-distributed hashes in a few cycles, and falls back to a slower function (strhashFallback) when AES is unavailable. The hash0 seed is mixed into every hash, so the same key hashes differently in different maps; that makes it much harder for an attacker to craft keys that all collide.

Small maps skip most of this machinery. When B is 0, there is a single bucket, and the runtime simply selects it and traverses it. Below nine elements a Go map behaves like a list, because the hashing algorithm is not used to pick among buckets. That is why tiny maps are not automatically faster than slices.

When a map outgrows its bucket array, the runtime allocates a new, larger array and keeps the old one in oldbuckets while it gradually moves entries across. By moving entries gradually, the runtime avoids a long pause on the insert that triggers the resize. A lookup is O(1) once the runtime has computed the hash, plus the cost of hashing the key itself.

Reading values: zero values and the comma-ok idiom

When you read m[key] and the key is absent, Go returns the zero value of the value type. For a map[string]int, a missing key returns 0; for map[string]string, it returns "". Go by Example demonstrates this behavior with a simple example.

The default is a problem when the zero value is a legitimate stored value. If you count page views with m[page]++, you cannot tell from the value alone whether a page has zero views or was never seen. Use the two-value form to solve this: v, ok := m[key] sets ok to true only when the key is present. Reach for it whenever a missing key and a zero value need different handling, such as cache lookups, configuration defaults, or membership checks.

Pre-size maps when you know the size

make(map[string]int, 100) does more than create an empty map. It tells the runtime how many entries to expect, so it allocates enough buckets up front and avoids the resizing and incremental migration that happen as the map grows. The arpalert performance notes recommend initializing with the expected size for exactly this reason. If you are loading a config file, a batch of rows, or a request header set, pass the known or estimated count to make.

Deleting entries and clearing the whole map

delete(m, key) removes a single key-value pair. To remove everything, use the clear builtin, which Go 1.21 added. It also handles keys that are never equal to anything, such as NaN floating-point keys, which delete cannot reliably remove. Go 101’s map optimization notes document both behaviors.

A map’s backing array, the underlying array of buckets that stores the entries, never shrinks. Even if you delete every entry or call clear, the runtime keeps the allocated buckets. That is usually good for performance, because a map that grows again does not need to reallocate, but it means a map that once held a million entries keeps that memory allocated after you empty it. If you need the memory back, drop the map variable and let the garbage collector reclaim it, then create a fresh map.

clear is not free. As of Go 1.24, on a map with at least one entry it takes time proportional to the size of the backing array, so the cost scales with capacity regardless of how full the map is. A map that grew large and then shrank still costs as much to clear as it did at its peak. One windows/amd64 user reported that clear performance in Go 1.25.0 was about 12% slower than 1.24.5 for maps with 30 to 100 entries, and that it got worse as size increased. That is a single report on one platform, so treat it as a signal to benchmark your own workload rather than a universal rule.

Key types and access patterns that change performance

The cheapest wins come from how you write updates and which key type you choose.

m[key] = m[key] + 1 hashes the key twice: once for the read and once for the write. m[key]++ hashes once. Go 101’s optimization notes call out this difference explicitly, so prefer the increment form in hot loops.

Key type affects both hashing cost and garbage collection. The garbage collector (GC) scans map entries only when the key or value types contain pointers. Strings contain a pointer to their backing data, so a map[string]T requires the collector to scan every entry. A [8]byte array contains no pointers, so map[[8]byte]T avoids that scanning entirely. If you index by fixed-size binary data, a byte array key can save GC time.

The compiler also special-cases key sizes of 4 and 8 bytes. map[[8]byte]V performs better than map[[5]byte]V, and map[int32]V better than map[int16]V. When you control the key representation, aligning it to 4 or 8 bytes pays off.

Byte-slice-to-string conversions behave differently on a map read than on a map write. _ = m[string(b)] does not allocate, because the runtime can hash the bytes directly. But m[string(b)] = v does allocate, because the map must store the string and therefore must copy the bytes. If you write to a map with a converted key, keep the conversion result in a variable when you reuse it.

For maps that hold complex structs, retrieve a pointer once instead of reaching into the map repeatedly. p := m[key]; p.Field = ... costs one lookup, while you cannot assign to a field of a struct stored in a map, because map elements are not addressable, and repeated reads of m[key] re-hash each time.

Finally, consider whether a map is the right structure at all for tiny datasets. Benchmarks with map[string]interface{} show that for fewer than eight items, a slice or list can be 5% to 50% faster, because the map’s hashing and bucket overhead outweighs a linear scan. That result depends on key type and access pattern, so measure it for your own data, but do not reach for a map by default when a small slice does the job.

Concurrency: when to reach for sync.Map

A standard Go map is not safe for concurrent use. If two goroutines write to the same map at the same time, the runtime can crash the program with a fatal "concurrent map writes" error. You can read from the map safely only while no goroutine is writing to it.

For concurrent access, the standard library provides sync.Map, added in Go 1.9. It grew out of the syncmap package in golang.org/x/sync, which the package documentation describes as safe for concurrent calls, with loads, stores, and deletes that take constant time on average. sync.Map is tuned for workloads where keys are written once and read many times, or where different goroutines work on disjoint keys. For a general-purpose concurrent map, a plain map guarded by a sync.RWMutex is often simpler and faster, because it avoids the overhead sync.Map pays to support its special cases. Benchmark both before choosing.

Iteration order is not guaranteed

When you range over a map, you visit entries in no defined order, and the runtime deliberately varies the starting point between iterations. If your code depends on a stable order, maintain a separate slice of keys and sort it before iterating. YourBasic Go’s sorting guide shows the standard pattern: collect the keys, sort them, then range over the sorted slice. Since Go 1.12, the fmt package prints maps in key-sorted order, which makes test output and debug logs stable even though range order is not.

Swiss Tables: the experimental future

The runtime contains four map implementations today, with fast paths for integer keys and string keys, plus a generic implementation. Their source file names end in _noswiss because they are the classic implementations, kept alongside an experimental alternative based on Swiss Tables, Google’s hash table design. Swiss Tables store metadata about each slot and use SIMD instructions, which let the CPU compare several values at once, to probe buckets in parallel. You activate the experimental implementation with GOEXPERIMENT=swissmap.

A GitHub issue on the Go runtime reports a performance regression for small Swiss Table maps with keys that don’t have a specialized fast path, and a proposed fix showed a geometric mean improvement on amd64 with SIMD optimizations. That patch was unmerged and untested on ARM and non-SIMD paths. Separately, an anecdotal blog post claims SwissMap’s promised performance gains of up to 50% did not hold up in production, though it offers no reproducible data. If your service is map-heavy, benchmark your actual workload on your Go version and hardware instead of assuming the new implementation is faster.

More in Web development Back to top ↑