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.
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 throwindex out of rangeerror.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 usingappendmethod.The speed difference is significant too. I benchmarked this for 10 million numbers. Using
make(pre-allocating) it is 4x faster.appendmakeThe first one took on average 84 ms, while second one only 19-22 ms.
Hope it helps...
wow amazing, great explanantion, thank you!