优化字节缓冲区相关代码

This commit is contained in:
刘祥超
2024-04-15 09:26:00 +08:00
parent 4bdd248f99
commit 5e7ea9a884
15 changed files with 243 additions and 57 deletions

View File

@@ -9,6 +9,10 @@ var BytePool4k = NewBytePool(4 << 10)
var BytePool16k = NewBytePool(16 << 10)
var BytePool32k = NewBytePool(32 << 10)
type BytesBuf struct {
Bytes []byte
}
// BytePool pool for get byte slice
type BytePool struct {
length int
@@ -24,20 +28,22 @@ func NewBytePool(length int) *BytePool {
length: length,
rawPool: &sync.Pool{
New: func() any {
return make([]byte, length)
return &BytesBuf{
Bytes: make([]byte, length),
}
},
},
}
}
// Get 获取一个新的byte slice
func (this *BytePool) Get() []byte {
return this.rawPool.Get().([]byte)
func (this *BytePool) Get() *BytesBuf {
return this.rawPool.Get().(*BytesBuf)
}
// Put 放回一个使用过的byte slice
func (this *BytePool) Put(b []byte) {
this.rawPool.Put(b)
func (this *BytePool) Put(ptr *BytesBuf) {
this.rawPool.Put(ptr)
}
// Length 单个字节slice长度