Skip to content

go.slice_append_in_loop

Performance Low

Detects slice appends in loops without pre-allocation, causing repeated reallocations.

Appending without pre-allocation:

  • Multiple reallocations — Slice grows exponentially, copying each time
  • Memory churn — Old backing arrays become garbage
  • GC pressure — More work for garbage collector
// ❌ Before (grows slice repeatedly)
var result []Item
for _, id := range ids {
result = append(result, fetchItem(id))
}
// ✅ After (pre-allocated)
result := make([]Item, 0, len(ids))
for _, id := range ids {
result = append(result, fetchItem(id))
}
  • append() in loops without make([]T, 0, n) initialization
  • Growing slices without capacity hint when size is known

Unfault adds slice pre-allocation:

result := make([]Item, 0, len(ids))