What is the point in setting a slice’s capacity?

A slice is really just a fancy way to manage an underlying array. It automatically tracks size, and re-allocates new space as needed.

As you append to a slice, the runtime doubles its capacity every time it exceeds its current capacity. It has to copy all of the elements to do that. If you know how big it will be before you start, you can avoid a few copy operations and memory allocations by grabbing it all up front.

When you make a slice providing capacity, you set the initial capacity, not any kind of limit.

See this blog post on slices for some interesting internal details of slices.

Leave a Comment