Sojeb Sikder

Go slice reallocation

Go slice reallocation

A slice in a Go is just a small structure containing:

  • Pointer to an underlying array
  • Length: number of elements currently stored
  • Capacity: size of underlying array

When we use append(), Go tries to add the element to the existing array. If there is no room left then Go:

  • Allocate a new larger array
  • Copies all existing elements into it
  • Update the slice to point to this new array

This is called slice reallocation

Let’s say we start with empty slice:

s := []int{}

Now append items

s = append(s, 1) // capacity maybe 1 or 2
s = append(s, 2)
s = append(s, 3) // when capacity is exceeded → reallocation

Once capacity is exceeded, Go grows the slice based on internal logic.

Typically:

  • If capacity < 256 then, capacity doubles
  • If capacity ≥ 256 then, capacity increases by ~1.25x

image.png

So, it helps to

  • Reduce memory waste
  • Improve performance cost

We can also control the reallocation with make() with estimated capacity, if we know our slice size ahead of time

users := make([]User, 0, 10_000)

or copy slices when needed

newSlice := append([]int(nil), oldSlice...)