Make slice helps on array shrinks

Hi, I knew slice is an abstraction of array which offers many standard lib functions; while expand(add/append) internal array get created and copy values from old to new array and drops old one, so “make” helps to avoid all these.

Will the same operations/behavior for shrink (delete of few values) also? if yes how? and the deleted cells/values of memory location has garbage values or it set to default values of type! or copy/shift happens internally.

Thanks,

Subbareddy Jangalapalli

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

yes, in-terms storage, as per standards vectors grow by 2 time of current capacity and array list grows by 3/2 times current capacity.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.