Sobes.tech
Senior

When does reallocation of the backing array occur during append?,

sobes.tech AI

Answer from AI

In Go, the append function adds elements to a slice. The slice contains a pointer to an underlying array, along with its length and capacity.

Reallocation of the backing array occurs when, after adding new elements, the slice's length exceeds its current capacity. In this case, a new array with increased capacity is created, data is copied into it, and the slice starts referencing this new array.

Example:

s := make([]int, 0, 2) // length 0, capacity 2
s = append(s, 1)        // length 1, capacity 2
s = append(s, 2)        // length 2, capacity 2
s = append(s, 3)        // length 3, capacity increases, reallocation occurs

Thus, reallocation occurs when append tries to add an element, and the current backing array has no free space (length == capacity). Usually, the new capacity is increased approximately twofold to reduce the number of reallocations during subsequent appends.