Optimize by pre-allocating slice
suggest changeAllocations are, relatively speaking, expensive.
Appending to a slice may allocate a new backing array when the new length exceeds the slice's capacity.
If you know the final size, allocate the required capacity in advance to avoid those intermediate allocations.
An estimate can still reduce allocations, but excessive preallocation wastes memory. Measure when this optimization matters.
Consider appending to an empty slice:
s := []byte("123456")
var d []byte
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d = append(d, s...)
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d = append(d, s...)
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d = append(d, s...)
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d: 0x0, len: 0, cap: 0
d: 0xc00007c018, len: 6, cap: 8
d: 0xc00007c040, len: 12, cap: 16
d: 0xc00007e040, len: 18, cap: 32
The results might vary depending on the version of the compiler and runtime. In this run, appending 6 bytes three times grew the capacity to 32.
%p on a slice prints the address of its first element. That address changes when append allocates a new backing array.
As the cap shows, the first allocation was for 8 bytes, then 16 bytes, and finally 32 bytes.
On each reallocation, the content had to be copied: 6 bytes, then 12, then 18. To store 18 bytes, the runtime copied 36 bytes along the way.
Memory allocations and copying memory take time.
For small slices the runtime often doubles the capacity, anticipating that more space might be needed.
We can be smarter than that and pre-allocate the slice:
s := []byte("123456")
d := make([]byte, 0, len(s)*4)
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d = append(d, s...)
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d = append(d, s...)
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d = append(d, s...)
d = append(d, s...)
fmt.Printf("d: %p, len: %d, cap: %d\n", d, len(d), cap(d))
d: 0xc0000140a0, len: 0, cap: 24
d: 0xc0000140a0, len: 6, cap: 24
d: 0xc0000140a0, len: 12, cap: 24
d: 0xc0000140a0, len: 24, cap: 24
Here we can see that we start with the right capacity from the beginning, and the runtime did not have to make an additional allocation or memory copy.