Allocation Budget (Go)
Topics: profiling, allocations, performance, testing.AllocsPerRun
Problem
Correct isn't enough — this one is graded on how much it allocates. Implement JoinInts so the
number of heap allocations stays constant, no matter how long the input is.
func JoinInts(xs []int) string
- Render
xs as decimal integers joined by single commas, no trailing comma:
{1,2,3} → "1,2,3", nil → "", {-5} → "-5".
- Allocation budget: ≤ 2 allocations per call, independent of
len(xs). The test uses
testing.AllocsPerRun on a 3-element and a 1000-element input and fails if either exceeds the
budget — so a per-element allocation that passes the small case still fails the large one.
The tempting solutions all allocate per element:
parts := make([]string, len(xs))
for i, x := range xs { parts[i] = strconv.Itoa(x) } // an alloc each
return strings.Join(parts, ",") // …plus more
The fix is to write everything into one pre-sized []byte with strconv.AppendInt (which
appends into the existing buffer — no allocation) and convert to a string once at the end. That's
two allocations — the buffer and the final string — regardless of input size.
Sign in to submit your solution.