Documentation
¶
Overview ¶
Package pool provides a free-list allocator for a single type whose values live off the Go heap and are recycled individually.
Get and Put never call the underlying allocator once a chunk has room, so they are the fastest way to allocate and free individual values in this module, and faster than new. The free list runs through the unused values themselves, so a pool adds no per-value overhead beyond rounding small types up to eight bytes. With the guards compiled in, each value also carries an 8-byte tag, and putting an Item twice, putting it into another pool, or reading it after Put panics.
Example ¶
package main
import (
"fmt"
memory "github.com/stubbedev/memory-go"
"github.com/stubbedev/memory-go/pool"
)
func main() {
var a memory.Local
defer a.Close()
type conn struct {
ID uint32
Bytes uint64
}
p, err := pool.New[conn](&a, 1024)
if err != nil {
panic(err)
}
defer p.Free()
c, err := p.Get()
if err != nil {
panic(err)
}
c.Value().ID = 7
fmt.Println(*c.Value(), p.Len())
p.Put(c)
reused, err := p.Get()
if err != nil {
panic(err)
}
fmt.Println(*reused.Value(), p.Len())
}
Output: {7 0} 1 {0 0} 1
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrChunkSize reports a chunk size that is not positive. ErrChunkSize = chunks.ErrSize // ErrZeroSize reports a type with no bytes to pool. ErrZeroSize = errors.New("pool of a zero-size type") )
Functions ¶
This section is empty.
Types ¶
type Item ¶
type Item[T any] struct { // contains filtered or unexported fields }
Item is a T owned by a Pool. It may be stored off-heap. The zero Item is nil.
type Pool ¶
type Pool[T any] struct { // contains filtered or unexported fields }
Pool hands out zeroed Ts and takes them back for reuse. It is not safe for concurrent use.
func New ¶
New returns a Pool that grows by chunkSize values at a time. It allocates the first chunk immediately.
func (*Pool[T]) Free ¶
Free releases every chunk, invalidating all Items. p must not be used afterwards.
func (*Pool[T]) GetUninit ¶ added in v0.4.0
GetUninit is Get without zeroing a recycled value, which then holds what it held when it was put back, with its first eight bytes overwritten. Use it only for a value that is written in full before it is read.