Skip to content

Commit

Permalink
pool: optimized the bytes buffer pool
Browse files Browse the repository at this point in the history
  • Loading branch information
nadoo committed Feb 26, 2025
1 parent bd40b07 commit 8e81e09
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
4 changes: 2 additions & 2 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 9 additions & 8 deletions pkg/pool/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package pool
import (
"math/bits"
"sync"
"unsafe"
)

const (
Expand All @@ -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)
}
}
}
Expand All @@ -30,21 +32,20 @@ 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<<i)[:size]
}
return pools[i].Get().([]byte)[:size]
}
return make([]byte, size)
}

// PutBuffer puts a buffer into pool.
func PutBuffer(buf []byte) {
if size := cap(buf); size >= 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))
}
}
}

0 comments on commit 8e81e09

Please sign in to comment.