Best practices for creating an empty array in GoLang?

I am curious about the best practices when initializing empty arrays.

i.e. Is there a difference between arr1, arr2 and arr3?

myArr1 := []int{}
myArr2 := make([]int,0)
var myArr3 []int

      

I know they make it empty []int

, but I'm wondering if one syntax is preferred over the others? Personally, I think the first one is the most readable, but that is beside the point. One of the key contention points could be the capacity of the array, presumably the default capacity is the same between three as it is undefined. Declares arrays of undefined capacity as "bad"? I can assume there are some costs involved, but how "bad" is it really?

/ TL; DR

  • Is there any difference between the three ways to make an empty array?
  • What is the default capacity for an array when undefined?
  • What is the cost of using arrays with undefined bandwidth?
+3


source to share


3 answers


First, it is a slice, not an array. Arrays and slices are very different in Go, arrays have a fixed size that is part of the type. I had problems with this at first :)



  • Not really. Any, if three are correct, and any difference should be too small to worry. In my own code, I usually use whatever is easiest for a particular case.
  • 0
  • Nothing, as long as you don't need to add an item, then whatever it takes to allocate the storage you need.
+1


source


Is there a difference between the three ways to create an empty array?

if it empty array

does len(array)==0

, the answer is no, but really only myArr3==nil

there is true

.

What is the default capacity for an array when undefined?



the default capacity will be the same with the line you specified.

What is the cost of using arrays with undefined bandwidth?

no one

+2


source


What is the cost of using arrays with undefined bandwidth?

There is a certain cost when you start filling out the slice. If you know how large a chunk should grow, you can allocate the capacity of the underlying array from the very begging, rather than reallocating every time the underlying array fills up.

Here's a simple example of timing:

package main

import "fmt"

func main() {

    limit := 500 * 1000 * 1000
    mySlice := make([]int, 0, limit) //vs mySlice := make([]int, 0)

    for i := 0; i < limit; i++ {
        mySlice = append(mySlice, i)
    }

    fmt.Println(len(mySlice))
}

      

On my machine:

time go run my_file.go

      

With preallocation:

real    0m2.129s
user    0m2.073s
sys     0m1.357s

      

Without prior use

real    0m7.673s
user    0m9.095s
sys     0m3.462s

      

+2


source







All Articles