DEV Community

Discussion on: Using NEW, instead of MAKE, to create slice

Collapse
 
freakynit profile image

With var a []int32, you are just declaring the variable, not allocating any space to underlying array. For example, this won't work: a[0] = 10. It'll throw index out of range error.
But if you use make, you specify the size, and the space is allocated then and there itself.
This becomes relevant of you know earlier how many elements this will hold. In that case you can straight away initialize the underlying array with that much memory, and directly refer using a[0] notation instead of using append method.

The speed difference is significant too. I benchmarked this for 10 million numbers. Using make(pre-allocating) it is 4x faster.

  1. Using append
func main() {
    var a []int32
    var i int32
    start := time.Now()
    for i = 0; i < 10_000_000; i++ {
        a = append(a, i)
    }
    fmt.Println("Time taken", time.Now().Sub(start).Milliseconds())
}
Enter fullscreen mode Exit fullscreen mode
  1. Pre-allocating using make
func main() {
    var a []int32 = make([]int32, 10_000_000)
    var i int32
    start := time.Now()
    for i = 0; i < 10_000_000; i++ {
        a[i] = i
    }
    fmt.Println("Time taken", time.Now().Sub(start).Milliseconds())
}
Enter fullscreen mode Exit fullscreen mode

The first one took on average 84 ms, while second one only 19-22 ms.

Hope it helps...

Collapse
 
nothinux profile image
Taufik Mulyana

wow amazing, great explanantion, thank you!