Go: Map Design by Code — Part II

Vincent
A Journey With Go
Published in
4 min readJul 1, 2019

--

Illustration created for “A Journey With Go”, made from the original Go Gopher, created by Renee French.

ℹ️ This article follows “Go: Map Design by Example” that describes the design of the map at a high level. I strongly suggest starting with Part I in order to understand the concept discussed here.

The internal design of the map shows us how it is optimized for performance, but also for memory management. Let’s start with the allocation of the map.

Map initialization

Go provides two ways to initialize our map and internal buckets:

  • Size explicitly defined by the user:
m := make(map[string]int, 10)
  • On demand with the first update of the map:
m := make(map[string]int)
m[`foo`] = 1

In the second example, at the creation of the map m, since the length has not been defined, no buckets will be created and Go is waiting for a first update to initialize the map. The second line will therefore run the bucket creation.

In both cases, the map can grow according to our need. The size defined in the first example will not stop the growth of the map if we need more than 10 keys, it just helps us to optimize the usage of the map since the on-demand growing has a cost for our code.

On-demand growth impact

--

--