Does Go have no real way to shrink a slice? Is that an issue?

To perform an, in effect, a realloc of a slice:

a = append([]T(nil), a[:newSize]...) // Thanks to @Dijkstra for pointing out the missing ellipsis.

If it does a copy of newSize elements to a new memory place or if it does an actual in place resize as in realloc(3) is at complete discretion of the compiler. You might want to investigate the current state and perhaps raise an issue if there’s a room for improvement in this.

However, this is likely a micro-optimization. The first source of performance enhancements lies almost always in selecting a better algorithm and/or a better data structure. Using a hugely sized vector to finally keep a few items only is probably not the best option wrt to memory consumption.

EDIT: The above is only partially correct. The compiler cannot, in the general case, derive if there are other pointers to the slice’s backing array. Thus the realloc is not applicable. The above snippet is actually guaranteed to peform a copy of ‘newSize’ elements. Sorry for any confusion possibly created.

Leave a Comment