Properly implement buffer pool
Some checks failed
Run Tests / Test (push) Failing after 18s
Benchmark BufferPool / RunBenchmarks (push) Failing after 19s

It wasn't reusing buffers, idiot idiot idiot...
This commit is contained in:
2024-07-24 19:05:49 +02:00
parent f30680c26f
commit a12c22587d
2 changed files with 53 additions and 20 deletions

View File

@@ -2,12 +2,20 @@ package pdu
import (
"bytes"
"log"
"sync"
)
type BufferPoolManager struct {
pools map[int]*sync.Pool
mu sync.RWMutex
debug bool
}
func (bpm *BufferPoolManager) logf(format string, args ...interface{}) {
if bpm.debug {
log.Printf(format, args...)
}
}
func NewBufferPoolManager() *BufferPoolManager {
@@ -26,9 +34,13 @@ func (bpm *BufferPoolManager) Get(size int) *bytes.Buffer {
// Double-check if another goroutine added the pool while we were waiting
pool, exists = bpm.pools[size]
if !exists {
bpm.logf("Creating new pool for size %d\n", size)
pool = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, size))
bpm.logf("Creating new buffer of size %d\n", size)
buf := bytes.NewBuffer(make([]byte, size))
buf.Reset()
return buf
},
}
bpm.pools[size] = pool
@@ -36,19 +48,23 @@ func (bpm *BufferPoolManager) Get(size int) *bytes.Buffer {
bpm.mu.Unlock()
}
return pool.Get().(*bytes.Buffer);
buf := pool.Get().(*bytes.Buffer)
bpm.logf("Returning buffer of size %d: %p\n", buf.Cap(), buf)
return buf
}
func (bpm *BufferPoolManager) Put(buf *bytes.Buffer) {
size := buf.Len()
size := buf.Cap()
bpm.mu.RLock()
pool, exists := bpm.pools[size]
bpm.mu.RUnlock()
if !exists {
bpm.logf("Cannot return %p, No pool for size %d\n", buf, size)
return
}
buf.Reset()
pool.Put(buf)
bpm.logf("Returned buffer of size %d: %p\n", size, buf)
}