In Golang you can allocate memory for a slice with the below syntax :
my_slice := make( []int, 0 )
And then later on I can add elements with the built-in append function as :
my_slice := append(my_slice, 23)
My question is, what's the difference between giving that zero ( or 2 or 5 or whatever) when "making" the slice if later on we can keep adding items as long as we wan?
Is there a performance bonus by trying to guess the capacity that slice will end up having?
The difference is that the memory for the slice is allocated upfront and len(mySlice)
returns the total slice length.
Performance wise it is beneficial to allocate the size upfront because when you call a = append(a, n)
the following occurs:
It calls the builtin append function and for that it first copies the a
slice (slice header, backing array is not part of the header), and it has to create a temporary slice for the variadic parameter which will contain the value n
.
Then it has to reslice a
if it has enough capacity like a = a[:len(a)+1]
- which involves assigning the new slice to a
inside the append function. If a would not have big enough capacity to do the append "in-place" then a new array would have to be allocated, content from slice copied, and then the assign / append be executed.
Then assigns n
to a [len(a)-1]
.
Then returns the new slice from the append function, and this new slice is assigned to the local variable a
.
Compared to a[i] = n
which is a simple assignment.