Go to content
Web development

Go Slices vs. Maps for Lookup-Heavy Code

When you write Go code that checks whether a value exists, fetches a value by key, or removes duplicates from a list, you are choosing between a slice and a map, and that choice sets how fast your code runs. A slice is a variable-length sequence backed by an array; you find a value by scanning the elements. A map is a hash table that stores key-value pairs and locates a value by hashing the key. For lookup-heavy code, the map is the default winner once the collection grows past a handful of elements, because the map answers each lookup in about the same time while scanning a slice takes longer as you add elements.

The slice keeps its place for tiny fixed sets and strict ordering, and when memory overhead matters more than lookup speed. To choose, you need to see how each structure performs internally and where the practical break-even point sits. You also need to know how nil values, iteration order, and preallocation affect that choice.

What each lookup costs

The map answers a key lookup in average constant time, O(1), because it does not examine the other entries. Since Go 1.24, the runtime uses a Swiss Tables implementation: a directory of tables, each holding groups of 8 slots. Each slot carries a one-byte preview of the key’s hash. The runtime compares those preview bytes with a few bitwise operations to check all 8 candidates in a group, then does a full key comparison only when a preview matches. Maps that have never held more than 8 entries skip the directory and table structure entirely.

The slice has no index of its contents. To find a value you call slices.Contains or write your own loop, and you scan elements from the start until you find a match. That is O(n): the cost grows linearly with the number of elements. If you sort the slice first, you can use binary search to cut the cost to O(log n), but you pay the sorting cost up front and you must keep the slice sorted as you insert new values.

The benchmarks match these mechanics. On an Apple M3 Pro, map lookup stayed around 16 ns/op regardless of dataset size. An older run on a 2015 MacBook Pro found map lookups in the tens of nanoseconds even as a 2500-element slice search crossed 1 microsecond. Both structures show zero allocations during lookup when they are preallocated, so the difference is time; neither structure produces garbage.

The small-set break-even point

Scanning a slice beats a map when the set is tiny. In the same 2015 benchmark, searching a 5-element slice took about 3.41 ns/op, while the map lookup took about 5.05 ns/op. The gap is small in absolute terms but real, and it explains the practical rule: unless your dataset has fewer than about 5 elements or you require strict ordering, the map is the better choice for lookups.

The crossover depends on where the match sits. A match at the front of a small slice is the fastest case; a match at the end or a missing value is the slowest. There is no universal threshold. When the set size falls between roughly 5 and a few dozen elements, measure your own hot path; outside that range, use the map.

For a small fixed set, such as a list of HTTP methods, the slice scan is fast and simple:

var methods = []string{"GET", "POST", "PUT", "DELETE"}

func isMethod(s string) bool {
    for _, m := range methods {
        if m == s {
            return true
        }
    }
    return false
}

At four elements, this loop beats a map lookup. It also keeps a stable order and needs no hash computation. The map becomes the better tool when the set is large and dynamic. A cache keyed by ID is the canonical case:

cache := make(map[string]*Entry, expectedEntries)

The map answers each lookup in about the same time as it grows. A slice-based cache would scan the whole collection on every miss, so the per-request cost rises with the number of cached entries, and deduplication would turn into a fresh O(n) scan for each new item.

Membership checks and deduplication

For a membership check, use a map whose values are empty structs, map[string]struct{}. The empty struct occupies no memory; the comma-ok idiom, the two-value form of a map read, distinguishes a present key from a missing one:

if _, ok := seen[name]; ok {
    // name is already in the set
}

To deduplicate, you iterate the source, write each element into the map if it is new, and append it to the result slice.

seen := make(map[string]struct{}, len(names))
unique := make([]string, 0, len(names))
for _, name := range names {
    if _, ok := seen[name]; ok {
        continue
    }
    seen[name] = struct{}{}
    unique = append(unique, name)
}

This pass runs in O(n) time because each membership test takes constant time. The map key must be a comparable type. Slices, maps, and functions cannot serve as keys, so for composite values you build a string key or use a struct whose fields are all comparable.

If you want to avoid the map entirely, you can sort the slice and check adjacent elements: creation in O(n log n), lookup in O(log n) with binary search, but insertion and deletion in O(n) because adding or removing an element shifts the rest. If you need a one-off cleanup of a list you already hold, you can sort it once and skip the map. If the set stays live and grows while you query it, the map answers each membership test in constant time.

Nil behavior, zero values, and iteration order

Slices and maps behave differently at their zero value, and the difference shows up as a runtime panic if you write to an uninitialized map. A nil slice is ready for append: append allocates a backing array when the slice has no capacity. A nil map is not writable: if you assign to it, the program panics because the map has no internal table to hold the entry. Initialize a map with make or a composite literal before writing to it.

The comma-ok idiom tells you whether a key exists, which matters when the value type’s zero value is meaningful. For optional string fields, the zero value is the empty string, so you cannot distinguish "never set" from "set to empty" without a wrapper such as sql.NullString. The %v format verb prints nil maps and nil slices the same as empty ones, so you cannot tell them apart in logs without an explicit nil check.

Map iteration order is randomized by design; the deliberate policy stops code from relying on it. Each map carries its own seed, so even two maps with identical contents can iterate in different orders. If your code needs a stable order, extract the keys, sort them, then iterate. The Go 1.23 maps and slices packages provide maps.Keys, maps.Values, and slices.Sorted for this pattern. A slice iterates in its natural order, which keeps output stable and avoids the sort.

If you iterate a map generically with reflect, expect heavy allocation; a benchmark with 8192 entries showed 32,879 allocations per operation versus 4 for a manual range loop. Prefer the direct loop or a generic helper.

Memory, allocation, and preallocation

A slice is a three-word header: a pointer to a backing array, a length, and a capacity. Passing a slice copies the header, not the elements beneath it. Sub-slicing shares the backing array, so writing through one slice can change what another slice sees. When append exceeds capacity, the runtime allocates a new backing array, copies the old elements, and returns a new header; it doubles capacity below 256 elements and gradually grows by 1.25x beyond that.

A map is a reference type; the variable points to the hash table. When one table overflows, the runtime rehashes only that table, whose size is bounded at 1024 entries, so the rehash cost stays local instead of spreading across the whole map.

If you know the final size, preallocate both: build the slice with make([]T, 0, n) or the map with make(map[K]V, n) so the runtime allocates once instead of growing repeatedly. As the benchmark above showed, lookups allocate nothing once the structures are preallocated; the difference shows up in the constant factors of the lookup and in the memory the hash table occupies.

Concurrent access

If multiple goroutines read and write the same collection, you need synchronization; neither a plain slice nor a plain map is safe. On the M3 Pro benchmark, a map guarded by sync.RWMutex cost about 42.3 ns/op for reads and 85.6 ns/op for writes, while sync.Map cost about 25.7 ns/op for reads and 120.7 ns/op for writes. sync.Map pays for its fast reads with slower writes, so it suits a read-mostly workload where keys are written once and read many times; for write-heavy traffic, the RWMutex-protected map is usually cheaper.

More in Web development Back to top ↑