goallocation

Make slices size


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?


Solution

  • 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:

    Compared to a[i] = n which is a simple assignment.