英文:
Why use make() to create a slice in Go?
问题
var a [4]int和b := make([]int, 4)之间有什么区别?b可以扩展,但a不能,对吗?但是如果我知道我确实需要4个元素,那么数组比切片更快吗?
var d []int和e := make([]int)之间有性能差异吗?f := make([]int, 5)相比于没有长度的情况下提供更好的性能,例如前5个元素吗?
c := make([]int, 5, 10)会分配比我可以访问的内存更多吗?
英文:
-
What is the difference between
var a [4]intandb := make([]int, 4)? Thebcan be extended, but nota, right? But if I know that I need really i.e. 4 elements, then is an array faster then a slice? -
Is there any performance difference between
var d []intande := make([]int)? Wouldf := make([]int, 5)provide more performance than without the length for the first i.e. 5 elements? -
Would this
c := make([]int, 5, 10)not allocate more memory than I can access?
答案1
得分: 11
a是一个数组,而b是一个切片。切片与数组的不同之处在于切片是指向数组的指针;切片是引用类型,这意味着如果你将一个切片赋给另一个切片,两者都指向同一个底层数组。例如,如果一个函数接受一个切片参数,并对切片的元素进行更改,这些更改将对调用者可见,类似于将指向底层数组的指针传递给函数(以上来自Learning Go)。你可以很容易地使用append和copy来操作切片。数组应该比切片稍微快一些,但差别不大。除非你确切地知道大小,否则最好使用切片,这样会更方便。
- make([]type, length, capacity),你可以估计大小和可能的容量以提高性能。
更多细节,请参考:Go Slices: usage and internals
英文:
ais an array, andbis a slice. What makes slices different from arrays is that a slice is a pointer to an array; slices are reference types, which means that if you assign one slice
to another, both refer to the same underlying array. For instance, if a function takes a
slice argument, changes it makes to the elements of the slice will be visible to the caller,
analogous to passing a pointer to the underlying array(Above from Learning Go). You can easily useappendandcopywith slice. Array should be a little faster than slice, but it doesn't make much difference. Unless you know the size exactly, it would be better to use slice which make things easy.- make([]type,length, capacity), you can estimate the size and possible capacity to improve the performance.
More details, you can refer:Go Slices: usage and internals
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论