mempool

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 1 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mempool provides deterministic, allocation-free object pools for hot game loops: Pool, Arena with its [Handle]s, and SlicePool. They reuse memory across frames and, unlike sync.Pool, never drop entries during garbage collection.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Arena

type Arena[T any] struct {
	// contains filtered or unexported fields
}

Arena is a dense, contiguous object pool with stable generational [Handle]s and O(1) swap-remove. Active values live contiguously in memory for cache-friendly iteration via Arena.ForEach, Arena.All, and Arena.Slice.

Example

An Arena stores values densely and hands out Handles that stay valid until their value is removed, and stop matching after.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/mempool"
)

type bullet struct{ X, Y, VX float32 }

func main() {
	arena := mempool.NewArena[bullet](4, nil)
	h1 := arena.Add(bullet{X: 1})
	h2 := arena.Add(bullet{X: 2})
	arena.Remove(h1)
	_, ok := arena.Get(h1)
	b, _ := arena.Get(h2)
	fmt.Println(arena.Len(), ok, b.X)
}
Output:
1 false 2

func NewArena

func NewArena[T any](initialCap int, reset func(*T)) *Arena[T]

NewArena creates an Arena with initial backing capacity for initialCap items. When reset is non-nil, it is invoked on removed or reset elements instead of zeroing them.

func (*Arena[T]) Add

func (a *Arena[T]) Add(v T) Handle

Add inserts v into the arena and returns its stable handle.

func (*Arena[T]) All

func (a *Arena[T]) All() iter.Seq2[Handle, *T]

All returns an iterator over every live (handle, pointer) pair in dense memory order, supporting early termination with break.

func (*Arena[T]) Alloc

func (a *Arena[T]) Alloc() (Handle, *T)

Alloc reserves a slot in the arena and returns its handle and a pointer to the newly reserved element for in-place initialization. The pointer is valid only until the next Add, Alloc, Remove, or Reset.

func (*Arena[T]) Cap

func (a *Arena[T]) Cap() int

Cap returns the current dense slice capacity of the arena.

func (*Arena[T]) ForEach

func (a *Arena[T]) ForEach(fn func(h Handle, v *T))

ForEach invokes fn for every live element in dense memory order. Callers must not add or remove elements while iterating.

func (*Arena[T]) Get

func (a *Arena[T]) Get(h Handle) (*T, bool)

Get resolves h to a pointer to its live element. It returns (nil, false) if h is zero or has been removed. The returned pointer is valid until the next mutation of the arena.

func (*Arena[T]) Has

func (a *Arena[T]) Has(h Handle) bool

Has reports whether h currently refers to a live element in the arena.

func (*Arena[T]) Len

func (a *Arena[T]) Len() int

Len returns the number of live elements in the arena.

func (*Arena[T]) Remove

func (a *Arena[T]) Remove(h Handle) bool

Remove deletes the element referenced by h in O(1) time via swap-remove and invalidates h. It returns false if h is already invalid.

func (*Arena[T]) Reset

func (a *Arena[T]) Reset()

Reset removes all live elements, invalidating all outstanding handles, while retaining all backing capacities for zero-allocation reuse.

func (*Arena[T]) Slice

func (a *Arena[T]) Slice() []T

Slice returns the contiguous slice of all live elements in the arena for direct cache-friendly iteration. Callers must not append to or re-slice the returned slice header in place of arena mutations.

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle is a stable generational reference to an element inside an Arena. Its zero value is always invalid.

func (Handle) IsZero

func (h Handle) IsZero() bool

IsZero reports whether h is the invalid zero handle.

type Pool

type Pool[T any] struct {
	// contains filtered or unexported fields
}

Pool is a deterministic, single-threaded object pool for game-loop entities such as bullets, enemies, particles, and transient structs.

Unlike sync.Pool, Pool never discards pooled objects on garbage collection: once warmed up, Acquire and Release run in O(1) time with 0 allocations. Pointers returned by Acquire remain stable across pool growth because memory is allocated in fixed chunks.

Example

A Pool reuses objects such as bullets, so firing does not allocate once the pool is warm.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/mempool"
)

type bullet struct{ X, Y, VX float32 }

func main() {
	pool := mempool.NewPool(8, func(b *bullet) { *b = bullet{} })
	pool.Prewarm(4)
	a := pool.Acquire()
	a.VX = 300
	b := pool.Acquire()
	fmt.Println(pool.Active(), pool.Free())
	pool.Release(a)
	pool.Release(b)
	c := pool.Acquire()
	fmt.Println(pool.Active(), c.VX)
}
Output:
2 6
1 0

func NewPool

func NewPool[T any](initialCap int, reset func(*T)) *Pool[T]

NewPool creates a Pool pre-populated with initialCap reusable objects.

When reset is non-nil, it is called on each object when released or when Reset is called, allowing callers to clear fields while keeping internal slice capacities. When reset is nil, objects are zeroed on release and Reset.

func (*Pool[T]) Acquire

func (p *Pool[T]) Acquire() *T

Acquire returns a pointer to a pooled object, allocating a new chunk only when no free objects remain.

func (*Pool[T]) Active

func (p *Pool[T]) Active() int

Active returns the number of objects currently checked out via Acquire.

func (*Pool[T]) Cap

func (p *Pool[T]) Cap() int

Cap returns the total number of slots managed by the pool.

func (*Pool[T]) Free

func (p *Pool[T]) Free() int

Free returns the number of objects immediately available without allocation.

func (*Pool[T]) Prewarm

func (p *Pool[T]) Prewarm(n int)

Prewarm ensures at least n objects are available in the free list so that subsequent Acquire calls do not allocate.

func (*Pool[T]) Release

func (p *Pool[T]) Release(v *T)

Release resets v and returns it to the free list for future Acquire calls. Passing nil is a no-op.

func (*Pool[T]) Reset

func (p *Pool[T]) Reset()

Reset reclaims all objects in the pool's chunks back to the free list without freeing backing memory. Every object is reset via the pool's reset hook (or zeroed if nil).

type SlicePool

type SlicePool[T any] struct {
	// contains filtered or unexported fields
}

SlicePool is a deterministic pool of reusable []T scratch slices (for query buffers, draw lists, particle emitters, etc.) that never drops slices on GC.

Example

A SlicePool lends out scratch slices for per-frame work and takes them back for reuse.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/mempool"
)

func main() {
	pool := mempool.NewSlicePool[int](4)
	s := pool.Acquire(16)
	s = append(s, 1, 2, 3)
	fmt.Println(len(s), cap(s) >= 16)
	pool.Release(s)
	fmt.Println(pool.Free(), len(pool.Acquire(8)))
}
Output:
3 true
1 0

func NewSlicePool

func NewSlicePool[T any](maxPooled int) *SlicePool[T]

NewSlicePool creates a SlicePool that retains up to maxPooled slices. When maxPooled <= 0, the pool retains all released slices without a cap.

func (*SlicePool[T]) Acquire

func (p *SlicePool[T]) Acquire(minCap int) []T

Acquire returns a zero-length slice with capacity at least minCap, reusing the tightest-fitting pooled slice when available.

func (*SlicePool[T]) Free

func (p *SlicePool[T]) Free() int

Free returns the number of slices currently stored in the pool.

func (*SlicePool[T]) Release

func (p *SlicePool[T]) Release(s []T)

Release clears s's backing elements (preventing retained pointers) and returns s[:0] to the pool for reuse.

func (*SlicePool[T]) Reset

func (p *SlicePool[T]) Reset()

Reset drops all pooled slice references from the pool.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL