Thanks for the clarification.

On Mon, Oct 22, 2018 at 13:13 Ian Lance Taylor <i...@golang.org> wrote:

> On Sun, Oct 21, 2018 at 8:34 PM, Fei Ding <fding...@gmail.com> wrote:
> >
> > I am studying golang source code, literally `go/src/runtime/chan.go`, the
> > question is in function `makechan`, when it comes to malloc memory for
> > channel with/without pointers, you guys did it as:
> >
> >
> > case elem.kind&kindNoPointers != 0:
> >     // Elements do not contain pointers.
> >     // Allocate hchan and buf in one call.
> >     c = (*hchan)(mallocgc(hchanSize+uintptr(size)*elem.size, nil, true))
> >     c.buf = add(unsafe.Pointer(c), hchanSize)
> > default:
> >     // Elements contain pointers.
> >     c = new(hchan)
> >     c.buf = mallocgc(uintptr(size)*elem.size, elem, true)
> >
> > So, my question is why to use two different ways to do this, (continuous
> vs
> > separated) ? and what's the difference/relationship between malloc and
> new?
>
> The hchan struct is designed so that it doesn't contain any pointers
> that the garbage collector needs to know about, as explained in the
> comment a few lines above the code you quote.  If the channel elements
> don't contain any pointers, then the garbage collector doesn't have to
> scan them.  So in that case we can allocate a single large block of
> memory to hold the hchan struct and the channel buffer, and the
> garbage collector will never to scan that large buffer.  That tends to
> give better memory cache behavior and slightly lessens the load on the
> garbage collector.  When the channel elements do have pointers, we
> allocate the channel buffer separately, as that is easier than
> building up a GC structure that handles both the hchan struct and the
> buffer.  The key difference is that in the no-pointer case we pass nil
> as the type argument to mallocgc, and in the pointer case we pass the
> element type.
>
> Calling new is equivalent to calling mallocgc(sizeof_type, type,
> true).  The only reason to call mallocgc is when the runtime wants to
> vary one of those arguments.
>
> 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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to