Golang / Golang Internals and Memory Management Interview Questions
How does append() work internally and what triggers a reallocation?
append(s, elems...) adds elements to slice s. The critical behaviour depends on whether the backing array has spare capacity:
- If
len(s) + len(elems) <= cap(s): no new allocation. The elements are written directly into the existing backing array beyonds.len. The returned slice shares the same backing array assbut with an incrementedlen. - If capacity is exhausted: Go allocates a new, larger backing array, copies all existing elements, then appends the new ones. The returned slice points to the new array; the original backing array is now unreferenced (and eligible for GC).
s := make([]int, 3, 5) // len=3 cap=5 â room for 2 more s2 := append(s, 10) // fits in cap â no reallocation // s and s2 SHARE the backing array until cap is exceeded s3 := append(s2, 20, 30) // cap exceeded â new backing array allocated // s, s2 still point to OLD array; s3 points to NEW array // ALWAYS use the returned value of append s = append(s, 99) // wrong to ignore the return â s might be outdated // Growth strategy (Go 1.18+) // cap < 256: double (newcap = oldcap * 2) // cap >= 256: grow ~25% + smooth correction to avoid thrashing // Pre-allocate when the final size is known names := make([]string, 0, 1000) // avoids N reallocations in a loop for _, n := range rawNames { names = append(names, n) }
The growth strategy changed in Go 1.18 from a simple doubling to a smoother formula: small slices (cap < 256) still double; larger slices grow by about 25% with a correction that blends the doubling and 25% rates. This avoids the cliff-edge behaviour at the transition point.
Hidden sharing trap: if you append to a sub-slice that still has spare capacity, the write goes into the original backing array, silently overwriting data seen by other slices sharing that array. Always use the three-index slice s[lo:hi:hi] to set cap equal to len when you want to guarantee a fresh allocation on the next append.
More Related questions...