How does the append function work when the underlying array reaches its capacity, and how does the growth factor change as the slice gets larger?
Last updated
When len == cap,
appendallocates a larger backing array, copies the elements, and returns a new slice. That is why you must writes = append(s, x).Growth is about 2x for small slices and tapers toward ~1.25x above ~256 elements, so appends stay amortized O(1) without wasting memory.
Preallocate with
make([]T, 0, n)when the size is known to avoid repeated reallocations.