mirror of
https://github.com/yusing/godoxy.git
synced 2026-03-31 22:23:14 +02:00
tweak: optimize memory allocation and increase throughput
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user