Skip to content

aipooljs: Object Pool

aipooljs solves a very specific problem: hot paths in games (bullets, particles, effects) create and destroy large numbers of same-shaped objects every frame, and the GC keeps chasing them. An object pool replaces those allocations with a fixed-size preallocated buffer, so acquire() / release() are both O(1) and produce no GC pressure.

終端機視窗
npm install aipooljs
import { createPool } from "aipooljs";
// 1. Preallocate a fixed-size buffer
const bullets = createPool({
create: () => ({ x: 0, y: 0, vx: 0, vy: 0, active: false }),
reset: (b) => {
// reset must use assignment, not delete (delete makes V8 downgrade the hidden class)
b.x = 0;
b.y = 0;
b.vx = 0;
b.vy = 0;
b.active = false;
},
size: 256,
});
// 2. Hot path: acquire is O(1) and does not allocate
function fireBullet(x: number, y: number, vx: number, vy: number) {
const b = bullets.acquire();
b.x = x;
b.y = y;
b.vx = vx;
b.vy = vy;
b.active = true;
return b;
}
// 3. Release when a bullet disappears: O(1), reset() runs first and then the object is returned
function recycleBullet(b: ReturnType<typeof fireBullet>) {
bullets.release(b);
}

Bullets, particles and hit effects are created and destroyed on the hot path over and over, which is exactly what an object pool is for. In the demo below the turret acquires bullets from a 256-slot pool and releases each one as it leaves the arena. Every few seconds a burst needs more bullets than the pool holds; with onOverflow: 'null', acquire() returns null and that shot is dropped. The status line shows alive, available, the total create() calls (flat once the pool is built) and the dropped shots.

Loading the interactive demo…

BulletSpawner: a 256-bullet object pool
Demo source
src/demos/pool-bullets.ts
/**
* BulletSpawner: a 256-bullet object pool with aipooljs.
*
* A turret sweeps its aim and fires glowing bullets (additive blend) into the arena. Each bullet
* is a Sprite `acquire()`d from a 256-slot pool and `release()`d the moment it leaves the arena:
* all 256 sprites are created with the pool and stay in the scene, hidden while they are free,
* so nothing is allocated or added to the scene graph after the pool is built. Every few seconds the turret fires a
* burst whose rate needs more than 256 bullets in flight; with `onOverflow: 'null'`, `acquire()`
* then returns null and the shot is dropped instead of growing the pool or throwing.
*
* The readout shows the pool's `alive` and `available`, how many times `create()` has run
* (256, all at construction, and flat after that), and the dropped shots.
*/
import { createPool } from 'aipooljs';
import { Container, Graphics, Sprite, type Application } from 'pixi.js';
import type { DemoContext, DemoHandle } from './types';
const ARENA = { width: 800, height: 400 };
const POOL_SIZE = 256;
const MUZZLE = { x: 70, y: 200 };
const BULLET_SPEED = 330; // px per second: about 2.2 s to cross the arena
const STEADY_RATE = 55; // shots per second, about 120 in flight
const BURST_RATE = 260; // shots per second during a burst, more than the pool can hold
const CYCLE_MS = 5000; // one steady stretch plus one burst
const BURST_MS = 1300; // the last part of each cycle
const WARM_UP_MS = 1500; // simulated before the first frame, so a paused demo is not empty
const MAX_STEP_MS = 50;
const REPORT_EVERY_MS = 250;
/** The pooled object: a sprite plus the per-shot state. */
interface Bullet {
sprite: Sprite;
vx: number;
vy: number;
burst: boolean; // fired during a burst; drawn in the second colour
}
function readColors(cssColor: DemoContext['cssColor']) {
return {
steady: cssColor('--sl-color-accent'),
burst: cssColor('--sl-color-orange'),
turret: cssColor('--sl-color-text'),
border: cssColor('--sl-color-gray-4'),
};
}
interface Stats {
alive: number;
available: number;
creates: number;
dropped: string;
rate: number;
}
const READOUT = {
'zh-TW': (s: Stats) =>
`存活 ${s.alive}|可用 ${s.available}|create() 呼叫 ${s.creates} 次|丟棄 ${s.dropped} 發|射速 ${s.rate} 發/秒`,
en: (s: Stats) =>
`Alive ${s.alive} | available ${s.available} | create() calls ${s.creates} | dropped ${s.dropped} | fire rate ${s.rate}/s`,
};
export function mount(app: Application, { lang, setStatus, cssColor }: DemoContext): DemoHandle {
// A soft dot: a faint halo under a bright core, white so each sprite can be tinted.
const dot = new Graphics().circle(0, 0, 6).fill({ color: 0xffffff, alpha: 0.25 }).circle(0, 0, 2.5).fill(0xffffff);
const texture = app.renderer.generateTexture({ target: dot, resolution: 2, antialias: true });
dot.destroy();
const layer = new Container();
const border = new Graphics();
const turret = new Graphics();
turret.position.set(MUZZLE.x, MUZZLE.y);
const arena = new Container();
arena.addChild(border, layer, turret);
app.stage.addChild(arena);
let colors = readColors(cssColor);
let creates = 0;
const pool = createPool<Bullet>({
size: POOL_SIZE,
create: () => {
creates++;
// Additive blending: overlapping bullets add up and glow.
const sprite = new Sprite({ texture, anchor: 0.5, blendMode: 'add', visible: false });
layer.addChild(sprite);
return { sprite, vx: 0, vy: 0, burst: false };
},
// Reset by assignment, never `delete`, so every bullet keeps the same hidden class.
reset: (bullet) => {
bullet.sprite.visible = false;
bullet.vx = 0;
bullet.vy = 0;
bullet.burst = false;
},
onOverflow: 'null', // acquire() returns null when all 256 are in flight
});
const live: Bullet[] = [];
let dropped = 0;
let clock = 0;
let owed = 0; // fractional shots carried to the next frame
let aim = 0;
const inBurst = () => clock % CYCLE_MS >= CYCLE_MS - BURST_MS;
function fire(): void {
const bullet = pool.acquire();
if (!bullet) {
dropped++; // the pool is empty: skip this shot
return;
}
bullet.burst = inBurst();
const angle = aim + (bullet.burst ? (Math.random() - 0.5) * 0.9 : 0);
bullet.vx = Math.cos(angle) * BULLET_SPEED;
bullet.vy = Math.sin(angle) * BULLET_SPEED;
bullet.sprite.position.set(MUZZLE.x + Math.cos(angle) * 24, MUZZLE.y + Math.sin(angle) * 24);
bullet.sprite.tint = bullet.burst ? colors.burst : colors.steady;
bullet.sprite.visible = true;
live.push(bullet);
}
/** Advances the simulation: sweep the aim, fire what the rate allows, move, recycle. */
function step(ms: number): void {
clock += ms;
aim = Math.sin(clock / 700) * 0.6;
owed += ((inBurst() ? BURST_RATE : STEADY_RATE) * ms) / 1000;
for (; owed >= 1; owed--) fire();
for (let i = live.length - 1; i >= 0; i--) {
const bullet = live[i];
const { position } = bullet.sprite;
position.x += (bullet.vx * ms) / 1000;
position.y += (bullet.vy * ms) / 1000;
if (position.x < 0 || position.x > ARENA.width || position.y < 0 || position.y > ARENA.height) {
live[i] = live[live.length - 1]; // swap-remove: order does not matter
live.pop();
pool.release(bullet); // reset() hides the sprite
}
}
}
const paint = () => {
border.clear().rect(0, 0, ARENA.width, ARENA.height).stroke({ width: 1, color: colors.border, alpha: 0.6 });
turret.clear().circle(0, 0, 14).fill({ color: colors.turret, alpha: 0.2 }).stroke({ width: 2, color: colors.turret });
turret.rect(8, -4, 18, 8).fill(colors.turret);
for (const bullet of live) bullet.sprite.tint = bullet.burst ? colors.burst : colors.steady;
};
const fit = () => {
const scale = Math.min(app.screen.width / ARENA.width, app.screen.height / ARENA.height);
arena.scale.set(scale);
arena.position.set((app.screen.width - ARENA.width * scale) / 2, (app.screen.height - ARENA.height * scale) / 2);
};
fit();
app.renderer.on('resize', fit);
const report = () =>
setStatus(
READOUT[lang]({
alive: pool.alive,
available: pool.available,
creates,
dropped: dropped.toLocaleString(lang),
rate: inBurst() ? BURST_RATE : STEADY_RATE,
}),
);
for (let t = 0; t < WARM_UP_MS; t += MAX_STEP_MS) step(MAX_STEP_MS);
paint();
turret.rotation = aim;
report();
let sinceReport = 0;
return {
update(deltaMS) {
step(Math.min(deltaMS, MAX_STEP_MS));
turret.rotation = aim;
sinceReport += deltaMS;
if (sinceReport >= REPORT_EVERY_MS) {
sinceReport = 0;
report();
}
},
onThemeChange() {
colors = readColors(cssColor);
paint();
},
dispose() {
app.renderer.off('resize', fit);
pool.dispose();
arena.destroy({ children: true }); // also the 256 pooled sprites
texture.destroy(true);
},
};
}

Fixed size, throws on overflow: acquire() throws PoolError when the pool is empty, forcing you to adjust the upstream spawn rate instead of letting the pool grow silently and make the worst case hard to predict. If you genuinely need elasticity, pass onOverflow: 'grow'.

Double-release detection: releasing the same object twice is a classic object pool bug. aipooljs tracks live objects with a Set, and a second release throws PoolError immediately.

Arguments are validated at construction: create and reset must both be functions, and the options object cannot be omitted. If create() or an overflow handler returns null / undefined, PoolError is thrown and the pool is left unchanged; use onOverflow: 'null' when you need “no object” semantics. If the fn of borrow(fn, { signal }) is not a function or signal is not an AbortSignal, PoolError is thrown before an object is taken out. Every PoolError message starts with aipooljs: , so match on the error class plus a regex, not on the full string.

reset does not use delete: deleting a property makes V8 downgrade the object to dictionary mode, which breaks hidden class optimisation and turns the whole hot path from monomorphic to megamorphic. The JSDoc states this rule explicitly.

createPool({
create, // () => T: creates the initial objects (must be a function and must not return null / undefined)
reset, // (obj: T) => void: resets an object on return (must be a function)
size, // number: pool size (required, non-negative integer)
onOverflow, // 'throw' (default) | 'null' | 'grow' | (pool) => T
})
  • Bullet/particle pools: the most typical use, paired with aiecsjs entity management
  • With aiquadtreejs: the pool manages object lifecycles, the quadtree manages spatial queries
  • DOM node recycling: <li> list items, canvas drawing objects and so on can be managed with the same pattern