Go Benchmark
Map Lookup vs Slice Search
When does a map actually beat a linear slice search for membership tests?
Checking whether a value is part of a known set is one of the most common operations in Go programs. The reflexive answer is "use a map[string]struct{}, maps are O(1)" — but hashing a key has a fixed cost, while scanning a small slice with slices.Contains is a tight, cache-friendly loop. This benchmark measures both approaches at 5, 10, 50, and 1000 elements to find the crossover point where the map's constant-time lookup overtakes the linear search. The result surprises most people: for small collections, the "slower" linear search wins.
1 CPU
32 CPUs
Uses a map[string]struct{} as a set and checks membership with _, ok := set[key]. Every lookup pays the fixed cost of hashing the key, but the cost stays flat no matter how many elements the set holds — the classic O(1) behavior maps are known for.
Uses slices.Contains(keys, key) from the standard library, which walks the slice front to back and compares each element. The work grows linearly with the slice length, but for small slices the sequential, cache-friendly memory access and lack of hashing make it faster than a map lookup.
Contributors