分配未初始化的切片

有没有办法在 Go 中分配一个未初始化的切片?一个常见的模式是创建一个给定大小的切片作为缓冲区,然后只使用它的一部分来接收数据。例如:


b := make([]byte, 0x20000) // b is zero initialized

n, err := conn.Read(b)

// do stuff with b[:n]. all of b is zeroed for no reason

当分配大量缓冲区时,此初始化可以累加,因为规范规定它将在分配时默认初始化数组。


大话西游666
浏览 188回答 2
2回答

函数式编程

您可以从bufs.Cache.Get获取非零字节缓冲区(或查看并发安全版本)。从文档:CCache注意:Get 返回的缓冲区不保证为零。例如,将缓冲区传递给 io.Reader 是可以的。如果您需要清零缓冲区,请使用 Cget。

慕容森

从技术上讲,您可以通过在 go 运行时之外分配内存并使用unsafe.Pointer,但这绝对是错误的做法。更好的解决方案是减少分配次数。将缓冲区移到循环外,或者,如果您需要每个 goroutine 缓冲区,请在池中分配几个缓冲区,并仅在需要时分配更多缓冲区。type BufferPool struct {&nbsp; &nbsp; Capacity int&nbsp; &nbsp; buffersize int&nbsp; &nbsp; buffers []byte&nbsp; &nbsp; lock sync.Mutex}func NewBufferPool(buffersize int, cap int) {&nbsp; &nbsp; ret := new(BufferPool)&nbsp; &nbsp; ret.Capacity = cap&nbsp; &nbsp; ret.buffersize = buffersize&nbsp; &nbsp; return ret}func (b *BufferPool) Alloc() []byte {&nbsp; &nbsp; b.lock.Lock()&nbsp; &nbsp; defer b.lock.Unlock()&nbsp; &nbsp; if len(b.buffers) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; return make([]byte, b.buffersize)&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; ret := b.buffers[len(b.buffers) - 1]&nbsp; &nbsp; &nbsp; &nbsp; b.buffers = b.buffers[0:len(b.buffers) - 1]&nbsp; &nbsp; &nbsp; &nbsp; return ret&nbsp; &nbsp; }}func (b *BufferPool) Free(buf []byte) {&nbsp; &nbsp; if len(buf) != b.buffersize {&nbsp; &nbsp; &nbsp; &nbsp; panic("illegal free")&nbsp; &nbsp; }&nbsp; &nbsp; b.lock.Lock()&nbsp; &nbsp; defer b.lock.Unlock()&nbsp; &nbsp; if len(b.buffers) < b.Capacity {&nbsp; &nbsp; &nbsp; &nbsp; b.buffers = append(b.buffers, buf)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go