Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

In Golang, we can use the builtin make() function to create a slice with a given initial length and capacity.

Consider the following lines, the slice's length is set to 1, and its capacity 3:

func main() {
    var slice = make([]int, 1, 3)
    slice[0] = 1
    slice = append(slice, 6, 0, 2, 4, 3, 1)
    fmt.Println(slice)
}

I was surprised to see that this program prints:

[1 6 0 2 4 3 1]

This got me wondering- what is the point of initially defining a slice's capacity if append() can simply blow past it? Are there performance gains for setting a sufficiently large capacity?

like image 429
Kenny Worden Avatar asked Jul 31 '17 19:07

Kenny Worden


People also ask

What is capacity in Go slice?

The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice. The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s) . You can extend a slice's length by re-slicing it, provided it has sufficient capacity.

What is capacity in make Golang?

It creates a new slice value that points to the original array." "To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it. "

What is Go capacity?

Go Slices Length and Capacity The length of a slice is the number of elements currently in the slice, while the capacity is the number of elements the slice can hold before needing to be reallocated.

What is the default capacity of slice in Golang?

Construction. The default zero value of a slice is nil . The functions len , cap and append all regard nil as an empty slice with 0 capacity.


1 Answers

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 tht initial capacity, not any kind of limit.

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

like image 56
captncraig Avatar answered Sep 20 '22 13:09

captncraig