Sobes.tech
Middle

How much does the size of a slice increase when using the append function?

sobes.tech AI

Answer from AI

The size of the slice may increase differently depending on the current capacity cap(slice):

  1. If there is insufficient capacity: The new capacity will be at least twice the current capacity if the current capacity is less than 1024. If it is greater than 1024, the new capacity will increase by 25% of the current capacity until it becomes sufficient. Then it may be rounded up.
  2. If there is enough capacity: The size of the slice increases exactly by the number of added elements, and the capacity remains unchanged.
// Example of append behavior when capacity is insufficient
s := make([]int, 0, 0) // size 0, cap 0
s = append(s, 1)       // size 1, cap 1. (0 -> 1)
s = append(s, 2)       // size 2, cap 2. (1 -> 2)
s = append(s, 3)       // size 3, cap 4. (2 -> 4)
s = append(s, 4)       // size 4, cap 4
s = append(s, 5)       // size 5, cap 8. (4 -> 8)

s2 := make([]int, 0, 1025) // size 0, cap 1025
s2 = append(s2, make([]int, 500)...) // size 500, cap 1025 (capacity is enough)
s2 = append(s2, make([]int, 1000)...) // size 1500, cap approximately 1025 + 1025*0.25 + epsilon

The specific capacity growth algorithm is inside the runtime and may change between Go versions. However, the general rules (doubling up to 1024, increasing by ~25% afterward) remain the same.