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?
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.More details, you can refer:Go Slices: usage and internals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With