Sobes.tech
Junior — Middle

Does the slice size always double when it is expanded?

sobes.tech AI

Answer from AI

No, doubling the size of a slice in Go during expansion does not always occur.

When a slice reaches its capacity and a new element needs to be added, Go allocates a new array with increased capacity and copies the data there. The rules for increasing capacity depend on the current size:

  • For small slices (usually less than 1024 elements), the size is typically doubled.
  • For larger slices, growth is more gradual — approximately 25% increase from the current capacity.

This is done to optimize memory usage and reduce the number of copies for large slices.

Example:

s := make([]int, 0, 2) // capacity 2
s = append(s, 1, 2)     // now length 2
s = append(s, 3)        // capacity will increase, most likely to 4 (doubling)

// If the slice is very large, for example with a capacity of 2000,
// upon expansion, the capacity will increase to about 2500 (not doubled)

Thus, doubling is a common but not the only scenario for slice expansion.

Does the slice size always double when it is… - sobes.tech