代码拉取完成,页面将自动刷新
package pool
import "sync"
const _MAX_RECYCLING_CAP = 4 << 10
// BytesSlicePool 定义 []byte 复用池的类型
type BytesSlicePool struct {
maxRecyclingCap int // 最大回收容量
pool *sync.Pool // 复用池
}
// NewBytesSlicePool 创建一个 []byte 复用池
func NewBytesSlicePool(sliceCap int, maxRecyclingCap ...int) *BytesSlicePool {
_maxRecyclingCap := _MAX_RECYCLING_CAP
if len(maxRecyclingCap) > 0 {
_maxRecyclingCap = maxRecyclingCap[0]
}
return &BytesSlicePool{
maxRecyclingCap: _maxRecyclingCap,
pool: &sync.Pool{
New: func() any {
buf := make([]byte, 0, sliceCap)
return &buf
},
},
}
}
// Alloc 分配一个 []byte 对象
func (own *BytesSlicePool) Alloc() []byte {
obj := own.pool.Get().(*[]byte)
return *obj
}
// Dealloc 释放当前 []byte 对象
func (own *BytesSlicePool) Dealloc(obj []byte) {
// 为了减少峰值分配,只向池返回较小的缓冲区
if cap(obj) <= own.maxRecyclingCap {
obj = (obj)[:0]
own.pool.Put(&obj)
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。