在 Go 中增加数组切片的容量相关的成本是多少?

What are the costs associated with increasing the capacity of an array slice in Go?

The Tour of Go 指出:"Slices can be created with the built-in make function; this is how you create dynamically-sized arrays. The make function allocates a zeroed array and returns a slice that refers to that array"。我想知道增加数组切片容量的成本是多少。

例如这两个数组切片之间的内存使用有什么不同:

a := make([]int, 0, 5) // len(a)=0, cap(a)=5
b := make([]int, 0, 1000) // len(b)=0, cap(b)=1000

给一个数组切片一个 x 的容量只是在内存中创建一个该切片的数组还是它做了其他事情?是让数组切片的容量大小接近其实际大小更好,还是增加容量以避免未来调整大小的成本更便宜?

提前感谢您的时间和智慧。

切片容量就是后备数组的大小。如果您知道您将追加到切片,并且希望避免将来的分配和复制,您只需要设置容量。如果您没有使用 append(或者通过切过长度手动调整大小的罕见情况),那么额外的容量就没有用。

在大多数情况下,附加到数组的相对成本很小,您可以让 append 根据需要分配和复制。