tweak: optimize memory allocation and increase throughput

This commit is contained in:
yusing
2025-05-16 07:15:45 +08:00
parent a162371ec5
commit 2e68baa93e
6 changed files with 252 additions and 40 deletions

View File

@@ -1,42 +1,48 @@
package synk
import "sync"
import (
"sync"
)
type (
// Pool is a wrapper of sync.Pool that limits the size of the object.
Pool[T any] struct {
pool sync.Pool
maxSize int
pool *sync.Pool
}
BytesPool = Pool[byte]
)
const (
DefaultInitBytes = 1024
DefaultMaxBytes = 1024 * 1024
)
const DefaultInitBytes = 32 * 1024
func NewPool[T any](initSize int, maxSize int) *Pool[T] {
func NewPool[T any](initSize int) *Pool[T] {
return &Pool[T]{
pool: sync.Pool{
pool: &sync.Pool{
New: func() any {
return make([]T, 0, initSize)
},
},
maxSize: maxSize,
}
}
func NewBytesPool(initSize int, maxSize int) *BytesPool {
return NewPool[byte](initSize, maxSize)
var bytesPool = NewPool[byte](DefaultInitBytes)
func NewBytesPool() *BytesPool {
return bytesPool
}
func (p *Pool[T]) Get() []T {
return p.pool.Get().([]T)
}
func (p *Pool[T]) Put(b []T) {
if cap(b) <= p.maxSize {
p.pool.Put(b[:0]) //nolint:staticcheck
func (p *Pool[T]) GetSized(size int) []T {
b := p.Get()
if cap(b) < size {
p.Put(b)
return make([]T, size)
}
return b[:size]
}
func (p *Pool[T]) Put(b []T) {
p.pool.Put(b[:0]) //nolint:staticcheck
}