On Thu, Mar 26, 2020 at 11:02 AM robfig <rob...@gmail.com> wrote:
>
> RE reducing the capacity, I want to distinguish freeing the memory (1) used 
> for the slice and (2) referred to by the slice elements. I can easily see 
> that freeing (1) is hard and not so beneficial, but I can't see why (2) would 
> be difficult, and the benefit seems potentially much larger. In our case, 
> each slice element has a handle to a sizable []byte, so that's why I was 
> interested to know if they would remain live.
>
> As an aside, (1) was addressed by Ian here:
> https://groups.google.com/d/msg/golang-nuts/sVhjhiYLXNg/YNZ_H-JsBAAJ

It's kind of the same problem for (2).  The garbage collector would
have to find every slice that referred to the memory in question and
check the capacity.  This is hard because the GC has no natural way to
go from the backing array pointer to the capacity associated with that
pointer.  In particular when slices are stored on the stack, there is
no requirement that the capacity be near the backing array pointer or
even to exist at all.  I suppose the GC could simply assume that all
backing array pointers on the stack referred to the entire array, but
then compiler optimizations would affect which elements were freed,
and the behavior would be somewhat unintuitive.

All in all, if you want to make sure that the slice elements are
cleared, you'll have to clear them yourself.  Or use a slice copy
rather than a simple slice expression.

Ian

-- 
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/CAOyqgcUhApbqw_Zcsa0cJ2ZjGz8Ov4gz0Zx-2BjqNXxgd5JjHQ%40mail.gmail.com.

Reply via email to