Go

What techniques do you use to reduce allocations in a hot path?

Question 344MediumGo 1.22 to 1.25
  1. Measure first: go test -bench . -benchmem, then pprof -sample_index=alloc_space.
  2. Preallocate: make([]T, 0, n) and make(map[K]V, n), and use strings.Builder.Grow.
  3. Reuse buffers: take a caller-supplied dst []byte in the strconv.AppendInt / AppendFormat style, reset slices with s = s[:0], or use sync.Pool.
  4. Avoid interface boxing in hot loops. Generics with concrete types, or typed functions, avoid converting to any.
  5. Pass and return values instead of pointers when small: returning a struct by value often keeps it on the stack.
  6. Avoid string/[]byte round trips. Use bytes functions directly, strconv.AppendX, or io.WriteString.
  7. Reduce pointers: []T instead of []*T, and indices instead of pointers in large graphs. This cuts GC scan work too.
  8. Keep constructors inlinable, so the caller's escape analysis applies to what they return.
// Allocates on every call
func keyA(id int, name string) string { return fmt.Sprintf("%d:%s", id, name) }

// Appends into a caller-provided buffer: zero allocs when reused
func keyB(dst []byte, id int, name string) []byte {
    dst = strconv.AppendInt(dst, int64(id), 10)
    dst = append(dst, ':')
    return append(dst, name...)
}

What the interviewer is looking for: an approach driven by profiling, not premature micro-optimisation. Fewer allocations mean less GC CPU and fewer mark assists, and therefore better tail latency.

More on Memory, GC & Runtime Internals

All 38 Memory, GC & Runtime Internals questions