Sobes.tech
Middle

How does the capacity of a slice change when it is expanded?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains a pointer to an array, a length, and a capacity. When adding elements using append, if the slice's length reaches its current capacity, a memory reallocation occurs: a new array with increased capacity is created, and data is copied into it.

The rules for changing capacity are not strictly fixed, but usually:

  • For small slices (up to 1024 elements), the capacity doubles.
  • For larger slices, the increase becomes more conservative (about 25% of the current capacity).

This allows balancing between the frequency of allocations and memory usage.

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, for example, to 4

Thus, the capacity of a slice grows exponentially when expanded, which optimizes the performance of adding elements.