duanqiang2977 2013-06-24 12:47
浏览 47

分配未初始化的切片

Is there some way to allocate an uninitialized slice in Go? A frequent pattern is to create a slice of a given size as a buffer, and then only use part of it to receive data. For example:

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

This initialization can add up when lots of buffers are being allocated, as the spec states it will default initialize the array on allocation.

  • 写回答

2条回答 默认 最新

  • dqyitt2954 2013-06-24 12:52
    关注

    Technically you could by allocating the memory outside the go runtime and using unsafe.Pointer, but this is definitely the wrong thing to do.

    A better solution is to reduce the number of allocations. Move buffers outside loops, or, if you need per goroutine buffers, allocate several of them in a pool and only allocate more when they're needed.

    type BufferPool struct {
        Capacity int
        buffersize int
        buffers []byte
        lock sync.Mutex
    }
    
    func NewBufferPool(buffersize int, cap int) {
        ret := new(BufferPool)
        ret.Capacity = cap
        ret.buffersize = buffersize
        return ret
    }
    
    func (b *BufferPool) Alloc() []byte {
        b.lock.Lock()
        defer b.lock.Unlock()
        if len(b.buffers) == 0 {
            return make([]byte, b.buffersize)
        } else {
            ret := b.buffers[len(b.buffers) - 1]
            b.buffers = b.buffers[0:len(b.buffers) - 1]
            return ret
        }
    }
    
    func (b *BufferPool) Free(buf []byte) {
        if len(buf) != b.buffersize {
            panic("illegal free")
        }
        b.lock.Lock()
        defer b.lock.Unlock()
        if len(b.buffers) < b.Capacity {
            b.buffers = append(b.buffers, buf)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题