Map length and capacity

May 15, 2023

Maps, like arrays and slices, have length.

Map types

The number of map elements is called its length. For a map m, it can be discovered using the built-in function len and may change during execution. …

This should be straight forward, but let’s consider a couple examples for good measure:

x := map[string]int{"a": 1, "b": 2, "c": 3}
fmt.Println(len(x)) // 3

var y map[string]float64
fmt.Println(len(y)) // 0

And somewhat deceptively, their capacity can also be set, or at least hinted at, but not read.

A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:

make(map[string]int)
make(map[string]int, 100)

Use a capacity hint when you know that a map you’re creating is likely or certain to grow to a certain size. Doing so gives the runtime the option to allocate enough memory for the specified capacity. Without this hint, the map will allocate new memory as it grows, contributing additional work to the garbage collector.

Notably, providing the capacity hint does not affect the length of the map.

x := make(map[string]int, 100)
fmt.Println(len(x)) // 0

The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps.

x := make(map[string]int, 1)
x["a"] = 1
x["b"] = 2
fmt.Println(len(x)) // 2, notably greater than initial capacity of 1

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this