* Henry <henry.adisuma...@gmail.com> [210810 01:26]:
> Just sharing some tips.
> 
> When working with slices, it is often a good idea to lend a helping hand to 
> the compiler. 
> 
> Don't declare something like this, unless you have no other choices.
> ```
> var slice []int
> ```

I believe this is bad advice.

First, if «slice» is to be used to hold a view into a backing array
generated elsewhere, e.g. the result of another function, attempting to
pre-allocate a backing array that will never be used is wasteful.

If you are using «slice» to build a result, and you have a good idea
what the final size of the result will be, preallocating something a bit
larger than the typical result indeed can be a good idea.

If you know for sure exactly what the initial size is going to be, than
preallocating with make() won't hurt, but doesn't do any better than
letting the first append do the allocation.

However, trying to _guess_ the initial size is often a waste of an
allocation.

  var slice []int

allocates the three-word slice header, but does not allocate any backing
array.  The first append will allocate a backing array of the correct
size.

Suppose you have a good idea that the initial size will be 5, so you
write

  var slice = make([]int, 0, 5)

But than it turns out that the initial size is really 6:

  slice = append(slice, data[i:j]...)

where j-i is 6, now the initial allocation of 5 elements was wasted.

If you are appending single elements in a loop, as in your simple
examples, than your advice is somewhat more sound.  In those cases, the
"initial" size is always 1, but the "final" size is its size at the end
of the loop, so making an initial estimate makes a lot more sense.

The take-away is that slice variables are used in many different ways,
and your advice holds in specific use cases, such as building a result
by appending one element at a time.  It does not hold in many real, more
sophisticated, use cases.

...Marvin

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/YRJrRpCVoXiS8c73%40basil.wdw.

Reply via email to