The Tour of Go states that: "Slices can be created with the built-in make function; this is how you create dynamically-sized arrays. The make function allocates a zeroed array and returns a slice that refers to that array". I'd like to know what the cost of increasing array slice capacity is.
E.g. what would be the difference in memory usage between these two array slices:
a := make([]int, 0, 5) // len(a)=0, cap(a)=5
b := make([]int, 0, 1000) // len(b)=0, cap(b)=1000
Does giving an array slice a capacity of x just create an array of that slice in memory or does it do something else? Is it better to keep the capacity size of an array slice close to its actual size or is it cheap to increase the capacity to avoid the costs of future resizing?
Thanks in advance for your time and wisdom.
The slice capacity is just the size of the backing array. You only need to set the capacity if you know you will be appending to the slice, and want to avoid future allocations and copies. If you're not using append
(or the rare case of manually resizing by slicing past the length), then the additional capacity serves no purpose.
In most cases, the relative cost of appending to an array is so little that you can just let append
allocate and copy as needed.