Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

  • 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?

like image 695
user977828 Avatar asked Feb 24 '13 02:02

user977828


1 Answers

  • 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

like image 118
Joe Avatar answered Oct 31 '22 11:10

Joe