为什么在Go中使用make()来创建切片?

huangapple go评论87阅读模式
英文:

Why use make() to create a slice in Go?

问题

var a [4]intb := make([]int, 4)之间有什么区别?b可以扩展,但a不能,对吗?但是如果我知道我确实需要4个元素,那么数组比切片更快吗?

var d []inte := make([]int)之间有性能差异吗?f := make([]int, 5)相比于没有长度的情况下提供更好的性能,例如前5个元素吗?

c := make([]int, 5, 10)会分配比我可以访问的内存更多吗?

英文:
  • What is the difference between var a [4]int and b := make([]int, 4)? The b can be extended, but not a, 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 []int and e := make([]int)? Would f := 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)。你可以很容易地使用appendcopy来操作切片。数组应该比切片稍微快一些,但差别不大。除非你确切地知道大小,否则最好使用切片,这样会更方便。

  • make([]type, length, capacity),你可以估计大小和可能的容量以提高性能。

更多细节,请参考:Go Slices: usage and internals

英文:
  • a is an array, and b is 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 use append and copy with 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

huangapple
  • 本文由 发表于 2013年2月24日 10:34:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/15048090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定