Memory 哪种通道类型在Go中使用的内存量最少?

Memory 哪种通道类型在Go中使用的内存量最少?,memory,go,resources,channel,internals,Memory,Go,Resources,Channel,Internals,我发现自己经常使用频道让事情停止。在这些情况下,信道仅被用作一种信令手段,并且没有任何数据被实际使用 例如: package main import ( "fmt" "time" ) func routine(stopChan chan bool) { fmt.Println("goroutine: I've started!") <-stopChan fmt.Println("goroutine: Cya'round pal") } func

我发现自己经常使用频道让事情停止。在这些情况下,信道仅被用作一种信令手段,并且没有任何数据被实际使用

例如:

package main

import (
    "fmt"
    "time"
)

func routine(stopChan chan bool) {
    fmt.Println("goroutine: I've started!")
    <-stopChan
    fmt.Println("goroutine: Cya'round pal")
}

func main() {
    fmt.Println("main: Sample program run started")

    stopChan := make(chan bool)

    go routine(stopChan)

    fmt.Println("main: Fired up the goroutine")

    stopChan <- true

    time.Sleep(1 * time.Second)

    fmt.Println("main: Sample program run finished")
}
如果你愿意的话,去果朗游乐场吧


我的问题是:

在Go中,哪种通道类型的内存占用最轻

e、 bool chan需要的开销比空结构{}chan少吗

chan bool

chan字节

chan接口{}

chan结构{}

还有什么?

看看频道的结构,它不是一个简单的结构:

type hchan struct {
    qcount   uint           // total data in the queue
    dataqsiz uint           // size of the circular queue
    buf      unsafe.Pointer // points to an array of dataqsiz elements
    elemsize uint16
    closed   uint32
    elemtype *_type // element type
    sendx    uint   // send index
    recvx    uint   // receive index
    recvq    waitq  // list of recv waiters
    sendq    waitq  // list of send waiters
    lock     mutex
}
服务员队列的要素还包括:

你看,很多字节。即使为空通道创建任何元素,这也可以忽略不计

但是,我希望所有空通道占用相同的空间量,而不管底层类型如何,因此如果您只想关闭通道,则不会有任何差异(实际元素似乎被指针持有)。一个快速测试可以备份它:

package main

import (
    "fmt"
    "time"
)

func main() {
    // channel type
    type xchan chan [64000]byte
    a := make([]xchan, 10000000) // 10 million
    for n := range a {
        a[n] = make(xchan)
    }
    fmt.Println("done")
    time.Sleep(time.Minute)
}
我看不出
chan struct{}
chan[64000]byte
之间有什么区别,它们都会在我的64位机器上产生约1GB的使用量,这让我相信在大约100字节的范围内创建单个通道的开销


总之,这并不重要。就我个人而言,我会使用
struct{}
,因为它是唯一真正的空类型(实际上大小为0),这清楚地表明没有发送任何有效负载的意图。

我没有在源代码中验证,但我希望通道本身的开销会主导字节、bool或struct{}对无缓冲通道的影响。
type sudog struct {
    g           *g
    selectdone  *uint32
    next        *sudog
    prev        *sudog
    elem        unsafe.Pointer // data element
    releasetime int64
    nrelease    int32  // -1 for acquire
    waitlink    *sudog // g.waiting list
}
package main

import (
    "fmt"
    "time"
)

func main() {
    // channel type
    type xchan chan [64000]byte
    a := make([]xchan, 10000000) // 10 million
    for n := range a {
        a[n] = make(xchan)
    }
    fmt.Println("done")
    time.Sleep(time.Minute)
}