go / intermediate
Snippet
Optimizing Performance with Slice Capacity
When using append, Go may need to reallocate the underlying array if the capacity is exceeded. By providing a capacity hint in make(), you reduce CPU overhead and memory fragmentation.
snippet.go
1
2
3
4
5
6
7
8
func efficientAppend() {// Pre-allocate capacity to avoid multiple reallocationsdata := make([]int, 0, 100)for i := 0; i < 100; i++ {data = append(data, i)}fmt.Println(len(data), cap(data))}
Breakdown
1
make([]int, 0, 100)
Initializes a slice with length 0 and capacity for 100 elements.
2
append(data, i)
Adds elements without triggering a new memory allocation until 100 is reached.
3
cap(data)
Returns the maximum number of elements the slice can hold without reallocating.