1 Star 0 Fork 1

leminewx/gokit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
bytes_slice_pool.go 1003 Bytes
一键复制 编辑 原始数据 按行查看 历史
leminewx 提交于 2025-07-28 22:34 +08:00 . v0.6.0.0
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)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/leminewx/gokit.git
git@gitee.com:leminewx/gokit.git
leminewx
gokit
gokit
fe1b72bb8dfe

搜索帮助