man go/maps

How Go maps work: Swiss tables since Go 1.24

lib / Go 11 mindraft

checked against: Go 1.27.4

What is a map[int]int in Go, and why does ranging over the same map twice give two different orders?

counts := map[int]int{}
for _, n := range ids {
	counts[n]++
}
for id, c := range counts {
	fmt.Println(id, c)
}

Since Go 1.24 the answer to the first question is a Swiss table, and since Go 1.26 it is the only one, because the older implementation is gone from the source. This article reads the implementation in go1.27.4, which lives in src/internal/runtime/maps/, and checks what it says with small programs run on an Apple M2 Pro. Every number below comes from that source, the release notes, or one of those programs.

The short version

A map is a directory of tables. Each table is an open-addressing hash table made of groups of 8 slots, and each group has one 8-byte control word: one byte per slot, saying whether the slot is empty, deleted, or full, and for a full slot holding 7 bits of the key’s hash. A lookup compares those 7 bits for all 8 slots at once and only compares real keys where the bits match. A table never grows past 1024 slots. Past that it splits in two, and the directory picks a table by the top bits of the hash. Iteration starts at random offsets, chosen again for every range loop.

Groups and control bytes

The package comment defines the pieces (map.go L22-L35): a slot holds one key and value, a group is 8 slots plus a control word, a table is a complete Swiss table, and the map’s directory is an array of tables. By default a group stores keys and values interleaved:

group for map[int]int (keys and values interleaved)
+-------------------------+-------+-------+-------+-----+-------+
| control word (8 bytes)  | k0 v0 | k1 v1 | k2 v2 | ... | k7 v7 |
+-------------------------+-------+-------+-------+-----+-------+
  byte i describes slot i:
    empty   1000 0000
    deleted 1111 1110
    full    0hhh hhhh   h = 7 low bits of the key's hash (H2)

The encoding is in group.go L115-L123. The 64-bit hash is cut in two (map.go L200-L211): the low 7 bits are H2, kept in the control byte, and the upper 57 bits are H1, used to pick where to start looking.

Keys or values larger than 128 bytes are not stored in the slot. The slot holds a pointer instead (abi/map.go L20-L23).

Finding a key

A lookup hashes the key with the map’s seed, uses H1 to choose a first group, and checks it with one word-sized operation: ctrlGroupMatchH2 XORs the control word with H2 copied into all 8 bytes, so a matching byte becomes zero, and a few more bit operations turn “which bytes are zero” into a bitset. That is 8 probes in one step, with plain 64-bit arithmetic (arm64 gets its own variant of the formula). Only slots in that bitset get a real key comparison. The package comment puts the false-positive rate per slot at 1 in 128, since H2 has 7 bits (map.go L60-L62).

If the group has no match and no empty slot, the search moves to another group. The probe sequence is triangular: offsets 0, 1, 3, 6, 10 and so on from the first group, which visits every group exactly once when the number of groups is a power of two (table.go L1324-L1355). A search stops at the first group that still has an empty slot, so a table can never be completely full. The load limit is 7 of every 8 slots (group.go L14-L20, table.go L116-L136).

Deleting from a group that is full can’t just mark the slot empty, because that would end other keys’ probe sequences too early. Such a slot gets the “deleted” tombstone instead (map.go L74-L84).

On this Mac the hash for an 8-byte key is AES-based (sysctl hw.optional.arm.FEAT_AES prints 1). On arm64 with the AES extension the runtime sets UseAeshash and fills the AES key schedule with random bytes at startup (runtime_alg.go L57-L69). On top of that every map has its own random seed (map.go L220-L221, L288).

Small maps skip the hash

A map that has never held more than 8 entries is a single group with no table and no directory (map.go L233-L243). With no probe sequence to protect, all 8 slots may be full. For 64-bit integer keys the compiler calls a specialised lookup (walk.go L192-L218), and on a small map that lookup doesn’t hash the key at all. It compares the key with each full slot in turn (runtime_fast64.go L38-L61).

Growing: tables and a directory

When a table runs out of room it is replaced: by one table of double the capacity while that stays at or under maxTableCapacity, which is 1024 slots, and otherwise by two tables of 1024 slots each (table.go L20, rehash, L1208-L1231, split, L1242-L1287). So no single grow copies more than 896 entries (7/8 of 1024), however large the map is. The source comment calls 1024 “completely made up”.

Which table a key belongs to is decided by extendible hashing: the top globalDepth bits of the hash index the directory. Two directory entries can point to the same table until that table splits. This is the package’s own diagram (map.go L104-L130):

directory (globalDepth=2)
+----+
| 00 | --\
+----+    +--> table (localDepth=1)
| 01 | --/
+----+
| 10 | ------> table (localDepth=2)
+----+
| 11 | ------> table (localDepth=2)
+----+

To watch it happen, this program inserts 5000 keys and records each insert that allocated memory:

package main

import (
	"fmt"
	"runtime"
)

type event struct {
	insert int
	bytes  uint64
}

func main() {
	events := make([]event, 0, 100)
	m := map[int]int{}
	var ms runtime.MemStats
	runtime.ReadMemStats(&ms)
	prev := ms.TotalAlloc
	for i := 1; i <= 5000; i++ {
		m[i] = i
		runtime.ReadMemStats(&ms)
		if ms.TotalAlloc != prev {
			events = append(events, event{i, ms.TotalAlloc - prev})
		}
		prev = ms.TotalAlloc
	}
	for _, e := range events {
		fmt.Printf("insert #%4d allocated %6d bytes\n", e.insert, e.bytes)
	}
}
$ go run grow.go
insert #   9 allocated    328 bytes
insert #  15 allocated    608 bytes
insert #  29 allocated   1184 bytes
insert #  57 allocated   2336 bytes
insert # 113 allocated   4896 bytes
insert # 225 allocated   9504 bytes
insert # 449 allocated  18464 bytes
insert # 897 allocated  36944 bytes
insert #1793 allocated  36960 bytes
insert #1796 allocated  36928 bytes
insert #3584 allocated  36992 bytes
insert #3587 allocated  36928 bytes
insert #3589 allocated  36928 bytes
insert #3595 allocated  36928 bytes

Every line matches the source. The first 8 keys fit in the first group, which the compiler placed on the stack here (go build -gcflags=-m reports map[int]int{} does not escape), so they allocate nothing. Key 9 turns the group into a table of 16 slots (growToTable, map.go L628-L629). After that the table doubles one insert past each 7/8 limit: 14 + 1, 28 + 1, 56 + 1, up to 896 + 1 = 897, where 2048 slots would exceed the cap and the table splits in two. From there the allocations stop doubling. Each of the two tables splits on its own when it passes 896 entries, at 1793 and 1796, and the four after that split near 3584. The exact insert numbers move a little between runs, because the seed decides which table each key lands in.

Iteration: random rotations

The spec only says the order “is not specified and is not guaranteed to be the same from one iteration to the next” (spec, For statements with range clause). The implementation randomises it on purpose. Iter.Init, which runs at the start of every range loop (through mapIterStart, runtime/map.go L156-L162), draws two random numbers: an offset into the slots and an offset into the directory (table.go L710-L714, L757-L758). Then it walks the slots in their usual order from that offset, wrapping around (L889, L1025). Within one table, every order is a rotation of one fixed sequence. This program counts the different orders in 20,000 loops over the same map:

package main

import (
	"fmt"
	"slices"
)

func keys(m map[int]int) []int {
	var ks []int
	for k := range m {
		ks = append(ks, k)
	}
	return ks
}

// isRotation reports whether b is a, read from another starting point.
func isRotation(a, b []int) bool {
	i := slices.Index(a, b[0])
	for j := range b {
		if a[(i+j)%len(a)] != b[j] {
			return false
		}
	}
	return true
}

func main() {
	for _, size := range []int{3, 8, 100, 1000} {
		m := map[int]int{}
		for i := range size {
			m[i] = i
		}
		first := keys(m)
		orders := map[string]bool{}
		allRotations := true
		for range 20000 {
			ks := keys(m)
			orders[fmt.Sprint(ks)] = true
			allRotations = allRotations && isRotation(first, ks)
		}
		fmt.Printf("%4d keys: %4d different orders, all rotations of one sequence: %v\n",
			size, len(orders), allRotations)
	}
}
$ go run order.go
   3 keys:    3 different orders, all rotations of one sequence: true
   8 keys:    8 different orders, all rotations of one sequence: true
 100 keys:  100 different orders, all rotations of one sequence: true
1000 keys: 1282 different orders, all rotations of one sequence: false

A map of n keys in one table has at most n possible orders, out of n! permutations, and these runs saw all n. If one loop over a three-key map gives 0 1 2, the others can only give 1 2 0 or 2 0 1, never 0 2 1. With 1000 keys the map has two tables, and the directory offset rotates the tables separately from the slots, so the orders stop being rotations of one sequence. Two maps of more than 8 keys, filled with the same keys in the same order, also iterate in different sequences, because their seeds differ and so do their slot layouts. In 1000 such pairs, 994 differed at 9 keys and all 1000 at 100 keys. A small map fills its group in insertion order, so at 3 and 8 keys no pair differed; only the starting point moves.

The iterator also has to survive a map that grows while you range over it. It keeps walking the old table it started on and looks each key up again in the new table to get the current value or skip a deleted entry (map.go L132-L179). The source comment calls this “the most complex part of the map”.

What it means for code

  • Code that depends on map order can’t pass by accident for long. If you need an order, sort the keys: slices.Sorted(maps.Keys(m)).
  • When ties are possible, a stable sort over map keys is not enough. The input to the sort is already in random order, so equal elements stay in a random order. Break ties with a second comparison instead.
  • If you know roughly how many keys are coming, make(map[K]V, hint) sizes the directory up front (NewMap, map.go L283-L330). The allocation program above, changed to start from make(map[int]int, 65536) and insert 43,282 keys, recorded no allocation at all after the make.

Curious facts

  • A three-key map has 3 possible iteration orders out of the 6 permutations. Iteration rotates a fixed slot order from a random start.
  • Small maps (up to 8 entries) with 64-bit integer keys find a key without hashing it, by comparing it with each full slot.
  • Deleting the last key of a map, or calling clear on it, gives the map a new random seed, “to make it more difficult for attackers to repeatedly trigger hash collisions” (map.go L695-L700, L784-L786).
  • The size cap of a table, 1024 slots, is marked in the source as a “completely made up value” to be tuned (table.go L14-L20).
  • go1.27 has an experiment, off by default, that stores a group’s 8 keys together and its 8 values together instead of interleaving them: GOEXPERIMENT=mapsplitgroup (flags.go L129-L132; it is not in the default list in buildcfg/exp.go L81-L89).

History

  • Go 1 (2012-03-28): the iteration order is defined as unpredictable, and each iteration starts at a random index.
  • Go 1.1: a new map implementation stops randomising maps of 8 or fewer entries.
  • Go 1.3 (2014-06-18): random iteration comes back for small maps “to flush out these bugs”.
  • Go 1.24 (2025-02-11): the built-in map becomes a Swiss table; GOEXPERIMENT=noswissmap brings back the old one.
  • Go 1.26 (2026-02-10): the old implementation is gone. runtime/map_noswiss.go and the SwissMap experiment flag exist at go1.25.0 and not at go1.26.0.

Sources

ls go/

  • draft How Go sorts: pdqsort in the slices packageWhat slices.Sort, slices.SortFunc and sort.Slice do in go1.27: pattern-defeating quicksort with insertion sort and a heapsort fallback, why it isn't stable, and what the stable sort costs instead.