Jay*_*lor 7 memory resources channel internals go
我发现自己经常使用频道让事情停止.在这些情况下,信道仅用作信令的手段,并且实际上没有使用任何数据.
例如:
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")
}
Run Code Online (Sandbox Code Playgroud)
// Sample output:
//
// main: Sample program run started
// main: Fired up the goroutine
// goroutine: I've started!
// goroutine: Cya'round pal
// main: Sample program run finished
Run Code Online (Sandbox Code Playgroud)
如果您在golang游乐场,请运行/查看它.
我的问题是:
Go中哪种通道类型的内存占用最轻?
例如,bool chan是否需要比空结构{} chan更少的开销?
chan bool
chan byte
chan interface{}
chan struct{}
...
别的什么?
看一下该频道的最新实现,它不是一个简单的结构:
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
}
Run Code Online (Sandbox Code Playgroud)
服务员队列的元素也很重:
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
}
Run Code Online (Sandbox Code Playgroud)
你看,很多字节.即使为空通道创建任何元素,这也可以忽略不计.
但是,我希望所有空通道占用相同的空间量,无论基础类型如何,因此如果您打算只关闭通道,则没有区别(实际元素似乎由指针保持).快速测试支持它:
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)
}
Run Code Online (Sandbox Code Playgroud)
我看到chan struct{}
和之间没有区别chan [64000]byte
,两者都导致我的64位机器上使用〜1GB的空间,这让我相信在大约100字节的某个地方创建单个通道的开销.
总之,它并不重要.我个人会使用struct{}
它,因为它是唯一真正空的类型(确实大小为0),清楚地表明没有任何有效载荷的内容被发送.
归档时间: |
|
查看次数: |
1919 次 |
最近记录: |