From 8e81e09a8f79198a832a4eb53e58b7b9a746e129 Mon Sep 17 00:00:00 2001 From: nadoo <287492+nadoo@users.noreply.github.com> Date: Wed, 26 Feb 2025 21:44:54 +0800 Subject: [PATCH] pool: optimized the bytes buffer pool --- .goreleaser.yml | 4 ++-- pkg/pool/buffer.go | 17 +++++++++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 9ba10bc..1dc3426 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -38,10 +38,10 @@ archives: builds: - default wrap_in_directory: true - format: tar.gz + formats: tar.gz format_overrides: - goos: windows - format: zip + formats: zip files: - LICENSE - README.md diff --git a/pkg/pool/buffer.go b/pkg/pool/buffer.go index 0f5acc9..155cd5d 100644 --- a/pkg/pool/buffer.go +++ b/pkg/pool/buffer.go @@ -3,6 +3,7 @@ package pool import ( "math/bits" "sync" + "unsafe" ) const ( @@ -17,11 +18,12 @@ var ( ) func init() { - for i := 0; i < num; i++ { + for i := range num { size := 1 << i sizes[i] = size pools[i].New = func() any { - return make([]byte, size) + buf := make([]byte, size) + return unsafe.SliceData(buf) } } } @@ -30,11 +32,10 @@ func init() { // otherwise, this function will call make([]byte, size) directly. func GetBuffer(size int) []byte { if size >= 1 && size <= maxsize { - i := bits.Len32(uint32(size)) - 1 - if sizes[i] < size { - i += 1 + i := bits.Len32(uint32(size - 1)) + if p := pools[i].Get().(*byte); p != nil { + return unsafe.Slice(p, 1<= 1 && size <= maxsize { - i := bits.Len32(uint32(size)) - 1 + i := bits.Len32(uint32(size - 1)) if sizes[i] == size { - pools[i].Put(buf) + pools[i].Put(unsafe.SliceData(buf)) } } }