Make slice helps on array shrinks

When you append to a full slice, a new slice is allocated with double the capacity of the old slice* and the elements from the old slice are copied into it. Using make with an initial length or capacity will reduce the number of times the slice is reallocated (e.g. appending 8 elements to a nil slice results in 4 allocations: 0 → 1, 1 → 2, 2 → 4, and then finally 4 → 8). If you specify an initial capacity of 8, then there are no reallocations.

The same thing does not happen when shrinking the length of a slice. The backing array does not automatically shrink. You can do this yourself if you need to. When a slice is shrunk, its elements are not set to nil and still hold garbage values. This can be a problem if your elements hold pointers because even though the elements are not accessible from the bounds of the slice, the memory is still considered accessible by the garbage collector, for example: What happens to "wasted" space in slices? - #10 by Keith_Randall

* The capacity is not actually always doubled. As capacities grow huge, it starts growing by 1.25x (or something similar) instead of doubling.

1 Like