英文:
What are the costs associated with increasing the capacity of an array slice in Go?
问题
The Tour of Go中提到:“可以使用内置的make函数创建切片;这是创建动态大小数组的方法。make函数分配一个零值数组,并返回一个指向该数组的切片”。我想知道增加数组切片容量的成本是多少。
例如,这两个数组切片之间的内存使用差异是多少:
a := make([]int, 0, 5) // len(a)=0, cap(a)=5
b := make([]int, 0, 1000) // len(b)=0, cap(b)=1000
给数组切片分配容量x只是在内存中创建一个该切片的数组,还是还有其他操作?是将数组切片的容量大小保持接近其实际大小更好,还是增加容量以避免未来调整大小的成本较低?
提前感谢您的时间和智慧。
英文:
The Tour of Go states that: "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". I'd like to know what the cost of increasing array slice capacity is.
E.g. what would be the difference in memory usage between these two array slices:
a := make([]int, 0, 5) // len(a)=0, cap(a)=5
b := make([]int, 0, 1000) // len(b)=0, cap(b)=1000
Does giving an array slice a capacity of x just create an array of that slice in memory or does it do something else? Is it better to keep the capacity size of an array slice close to its actual size or is it cheap to increase the capacity to avoid the costs of future resizing?
Thanks in advance for your time and wisdom.
答案1
得分: 1
切片容量只是底层数组的大小。只有在知道将要向切片追加元素并且希望避免未来的内存分配和复制时,才需要设置容量。如果不使用append
函数(或者极少数情况下手动通过切片来调整大小),那么额外的容量就没有任何作用。
在大多数情况下,向数组追加元素的相对成本非常小,因此可以让append
函数根据需要进行内存分配和复制。
英文:
The slice capacity is just the size of the backing array. You only need to set the capacity if you know you will be appending to the slice, and want to avoid future allocations and copies. If you're not using append
(or the rare case of manually resizing by slicing past the length), then the additional capacity serves no purpose.
In most cases, the relative cost of appending to an array is so little that you can just let append
allocate and copy as needed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论