freelist + benchmarking

This commit is contained in:
lehugueni
2024-12-02 12:26:42 +01:00
parent 6cb65c300a
commit 0504cfa1a6
4 changed files with 283 additions and 7 deletions

View File

@@ -6,6 +6,7 @@ type BufferPool[T any] interface {
Get() T
Put(T)
}
type SyncPool[T any] struct {
pool *sync.Pool
}
@@ -26,3 +27,39 @@ func (spool *SyncPool[T]) Get() T {
func (spool *SyncPool[T]) Put(buff T) {
spool.pool.Put(buff)
}
type FreeList[T any] struct {
pool chan T
newObject func() T
capacity int
}
func NewFreeList[T any](capacity int, f func() T) *FreeList[T] {
pool := make(chan T, capacity)
for i := 0; i < capacity; i++ {
pool <- f()
}
return &FreeList[T]{
pool: pool,
newObject: f,
capacity: capacity,
}
}
func (fl *FreeList[T]) Get() T {
var obj T
select {
case obj = <-fl.pool:
default:
obj = fl.newObject()
}
return obj
}
func (fl *FreeList[T]) Put(obj T) {
select {
case fl.pool <- obj:
default:
}
}