Can You Make Append Allocation-free When The
Fast recall
Quick revision
Core answer
Practical understanding of Append And Growth.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
When you know how many elements you'll end up with — a loop over a known input, a transformation with 1:1 output — you can pre-allocate the destination with capacity and let append only ever take its in-place path.
out := make([]string, 0, len(input))
for _, v := range input {
out = append(out, transform(v))
}Each append writes into the next spare slot — no reallocation, no copies of the growing prefix, no transient garbage arrays. The whole build is one allocation of len(input) slots and n direct stores.
The pattern applies anywhere the bound is knowable: a filter that keeps at most len(input) items, a batch of results sized by request, a buffer for a read whose maximum size is documented. Where the size is only estimated, the capacity hint still amortizes growth even if it misses.
This is the standard-libraray idiom too — bytes.Buffer grows similarly behind the scenes, and slices pre-sized in hot paths are one of the easiest real performance wins in Go.
Can You Make Append Allocation-free When The
Direct Answer
make([]T, 0, n) up front — every append then writes in place within capacity. One allocation instead of the grow-copy chain.
Deep Dive & Architecture
Why is this such a win? Compare the allocation behavior:
Growth mode (no pre-size): appending 1000 elements to a zero-cap slice allocates and copies at roughly every doubling — the array moves through cap 1, 2, 4, 8 ... 1024, copying the prefix each time. Total element copies: about 2000 for 1000 appends. Plus each abandoned array is garbage for the GC to collect.
Pre-sized mode: make([]T, 0, 1000) allocates once, appends are pointer-bumps, total copies zero. Same final slice, radically different work.
That's the amortized-analysis story from dynamic arrays, applied by hand. The runtime's doubling keeps append O(1) average even without pre-sizing — you never need this for correctness — but the constant factors differ by orders of magnitude in hot loops. Profile first, but when a loop's shape makes the final size knowable, this is the cheapest optimization in the language.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Append And Growth, and when would you use it?
- When would you use Append And Growth in a real project?
- How would you compare Append And Growth with an alternative?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.