Go

Go

Made by DeepSource

Multiple append can be combined into a single call CRT-P0001

Performance
Major
Autofix

Multiple calls for append could be combined into a single call for append.

The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements, but if capacity is not enough, then append will allocate a new underlying array and return the updated slice. Therefore, it is necessary to store the result of append, often in the variable holding the slice itself. Appending calls in a single call of append allocates memory just once to accommodate all the elements to be appended. Whereas multiple calls to append introduce many overheads, most notably being the possibility of more calls for memory allocation because the total number of elements to be appended over multiple calls of append is unknown beforehand, resulting in inaccurate preallocation.

Read more about a similar implementation for append. Hence, a single call to append is recommended.

Bad practice

xs = append(xs, 1)
xs = append(xs, 2)
xs = append(xs, 3)
xs = append(xs, 4)
xs = append(xs, 5)

Recommended

xs = append(xs, 1, 2, 3, 4, 5)