DEV Community

mustafa morbel
mustafa morbel

Posted on Originally published at Medium

Return the Cart, Clear the Exit: Object Pools and Zero-Allocation Loops in Canvas

Originally published on Medium. Read on Medium for free via Friend Link.

๐ŸŽฎ Try the Live Pooled vs. Unpooled Demo ยท ๐Ÿ“ฆ GitHub Repo & 6 Vitest Suites ยท โšก Get the TS 2D Canvas Physics Starter Kit

Interactive Object Pool vs. Unpooled Demo Preview

Split comparison showing chaotic abandoned shopping carts labeled 36,000 objects and 3,600 arrays on the left versus a tidy cart return bay labeled 347 objects and 0 arrays on the right, both with 279 surviving particles over 60 seconds.
Recycling particles with an object pool drops 36,000 object allocations and 3,600 array allocations down to 347 objects and zero arrays over a 60-second scene.

Quick takeaways

  • Replacing push({...}) and filter() with a TypeScript Pool<T> cuts particle allocations from 36,000 down to 347 (the exact high-water mark) over 3,600 frames.
  • An O(1) backward swap-remove removes all 3,600 per-frame array allocations.
  • Writing into an out vector (scaleAndAdd) avoids 240,000 temporary Vec2 allocations per second across 1,000 physics bodies.
  • V8's young-generation scavenger clears sporadic allocations in under a millisecond, so only add a pool when profiling shows a sawtooth heap curve.

At a packed supermarket on a Saturday afternoon, if every shopper abandons their cart right outside the exit instead of rolling it back into the return bay, a wall of metal carts piles up at the door within minutes. Incoming shoppers cannot find a cart, and people leaving can barely squeeze through. Soon traffic stops altogether. Staff block off the exit lane, everyone waits while workers haul the pile back to the entrance, and only then does the store move again.

A default particle system in a browser game behaves the same way. In our physics engine article, sparks flew whenever a block cracked. In a falling ball game, every catch triggered a burst. Both used the same familiar pattern: particles.push({...}) on every burst, and particles = particles.filter(p => p.life > 0) on every frame. With a dozen sparks, nobody notices. Once hundreds of particles spawn and expire every second, those abandoned carts pile up at the exit until the Garbage Collector (GC) has to block the lane and clear the jam. When the GC halts the main thread to reclaim memory, a frame drops and your 60 FPS animation hitches.

Instead of abandoning carts at the exit, we can roll them back into a return bay. We will inspect the GC sawtooth pattern in Chrome DevTools, build a generic, type-safe Pool<T>, wire it into a particle system with swap-remove, remove temporary vector allocations from the integration loop, and benchmark both heavy and light workloads to see when pooling helps and when it does not.

The sawtooth curve

JavaScript manages memory automatically. When you write { x: 0, y: 0 }, the engine allocates space on the heap; once nothing references that object, the garbage collector reclaims it without you ever calling free(). In most web apps, that convenience is great. Inside a 60 FPS game loop, though, constant allocation turns into a recurring pause.

Here is the simplified spawn and update logic from our physics demo:

// src/particle.ts โ€” baseline pattern BEFORE optimization (churn)
export interface Particle {
  x: number;
  y: number;
  vx: number;
  vy: number;
  life: number;
  max: number;
}

let particles: Particle[] = [];

export function spawn(x: number, y: number, count: number, rng: () => number) {
  for (let i = 0; i < count; i++) {
    const a = rng() * Math.PI * 2;
    const speed = 40 + rng() * 150;
    const life = 0.3 + rng() * 0.4;
    particles.push({
      x,
      y,
      vx: Math.cos(a) * speed,
      vy: Math.sin(a) * speed,
      life,
      max: life,
    }); // every call: a brand new object on the heap
  }
}

export function update(dt: number) {
  for (const p of particles) {
    p.life -= dt;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    p.vy += 220 * dt;
  }
  particles = particles.filter((p) => p.life > 0); // every frame: a brand new array
}
Enter fullscreen mode Exit fullscreen mode

This code produces garbage in two places. First, every push({...}) allocates a fresh Particle object on the heap. Second, particles.filter(...) allocates a new array on every frame just to drop expired items. If 500 particles are active and one spark dies, filter still allocates a new array and copies the 499 surviving references into it, 60 times a second.

Even though V8's garbage collector is fast, a major collection cycle still has to pause JavaScript on the main thread (a stop-the-world pause). That pause is what drops frames.

You can see this directly in Chrome DevTools. Open the Performance tab, check the Memory box, hit Record, trigger plenty of particle bursts for a few seconds, and stop recording. Look at two tracks:

  • In the JS Heap graph, memory climbs steadily as objects accumulate, then plunges vertically when the garbage collector sweeps the heap. That repeating rise-and-drop shape is a sawtooth curve. Steeper, more frequent teeth mean heavier allocation pressure.
  • In the Frames track, yellow Major GC or Minor GC blocks line up with each drop in the heap graph, often alongside red markers for dropped frames. Those red markers are the stutters the player feels.

The goal is to flatten that sawtooth into a horizontal line by avoiding allocations during gameplay.

Building a generic object pool

Comic-style diagram titled The Cart Pool showing shoppers acquiring carts from a free array, releasing them back, and an attendant resetting stale state before reuse.
The object pool lifecycle: acquire from free[], release back to the bay, and reset every field so stale state never leaks.

Supermarkets solve the cart problem with a return bay at the entrance. You grab an empty cart (acquire), shop with it, and roll it back into the bay when you finish (release). Any leftover receipt or item gets cleared out (reset) so the cart is ready for the next person.

An object pool works the same way. Here is a generic, type-safe Pool<T> in TypeScript:

// src/pool.ts
export interface PoolOptions<T> {
  create: () => T; // how a new object is produced
  reset: (obj: T) => void; // how a returned object is cleared
  initial?: number; // how many to keep ready up front
}

export class Pool<T> {
  private free: T[] = []; // the empty carts in the return bay
  private create: () => T;
  private reset: (obj: T) => void;

  created = 0; // total carts put into circulation (high-water mark)

  constructor(opts: PoolOptions<T>) {
    this.create = opts.create;
    this.reset = opts.reset;
    for (let i = 0; i < (opts.initial ?? 0); i++) {
      this.free.push(this.make());
    }
  }

  private make(): T {
    this.created++;
    return this.create();
  }

  acquire(): T {
    // If there is a cart in the bay, hand it over; otherwise roll out a new one.
    return this.free.pop() ?? this.make();
  }

  release(obj: T): void {
    this.reset(obj); // empty it first
    this.free.push(obj); // then push it back into the bay
  }

  get available(): number {
    return this.free.length;
  }
}
Enter fullscreen mode Exit fullscreen mode

Everything depends on one line inside acquire: this.free.pop() ?? this.make(). When an object is waiting in free, we hand it back with zero heap allocation. We only call make() when the bay is empty.

This naturally caps allocations at the high-water mark: the highest number of objects your game needs alive at the same time. If your scene never has more than 347 particles on screen at once, the pool creates 347 objects over its entire lifetime and stops there. During the first few seconds, the pool warms up to that peak. After that, created stays flat and heap allocations drop to zero.

reset is a dedicated callback because a returned object still holds whatever values it had when it died. If the next caller gets an unemptied object and does not overwrite every field, you end up with ghost bugs.

Comic-style illustration titled The Particle That Flew Backward showing one glowing blue particle shooting backward with stale vy velocity because vy was not reset to 0 on release.
Forgetting to reset a single field (vy = 0) leaves stale state on recycled particles and causes subtle ghost bugs.

Wiring the particle system to the pool

Diagram comparing array filter versus swap-remove using shopping carts: filter copies 499 surviving carts into a new array, while swap-remove moves the last cart into the expired slot with 1 move and pops the end.
filter() copies 499 surviving references into a brand-new array every frame; backward swap-remove does one swap, pops the tail, and releases the dead particle in O(1).

With Pool<T> ready, we can replace push({...}) and filter() in the particle emitter. When a particle spawns, we call acquire; when it expires, we call release.

// src/particle-system.ts
import { Pool } from "./pool";
import type { Particle } from "./particle";

export class ParticleSystem {
  private pool: Pool<Particle>;
  private active: Particle[] = []; // the live particles on screen

  constructor(initial = 256) {
    this.pool = new Pool<Particle>({
      initial,
      create: () => ({ x: 0, y: 0, vx: 0, vy: 0, life: 0, max: 0 }),
      reset: (p) => {
        p.x = 0;
        p.y = 0;
        p.vx = 0;
        p.vy = 0;
        p.life = 0;
        p.max = 0;
      },
    });
  }

  burst(x: number, y: number, count: number, rng: () => number) {
    for (let i = 0; i < count; i++) {
      const p = this.pool.acquire(); // not new: taken from the bay
      const a = rng() * Math.PI * 2;
      const speed = 40 + rng() * 150;
      const life = 0.3 + rng() * 0.4;
      p.x = x;
      p.y = y;
      p.vx = Math.cos(a) * speed;
      p.vy = Math.sin(a) * speed;
      p.life = life;
      p.max = life;
      this.active.push(p);
    }
  }

  update(dt: number) {
    // No filter. When one dies, return it to the pool and move the last one into its slot.
    for (let i = this.active.length - 1; i >= 0; i--) {
      const p = this.active[i];
      p.life -= dt;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.vy += 220 * dt;

      if (p.life <= 0) {
        this.pool.release(p); // return the cart to the bay
        this.active[i] = this.active[this.active.length - 1]; // swap-remove
        this.active.pop();
      }
    }
  }

  get activeCount(): number {
    return this.active.length;
  }

  // Walk the live particles for drawing โ€” without a copy or a new array (zero allocation).
  get particles(): readonly Particle[] {
    return this.active;
  }

  get allocations(): number {
    return this.pool.created;
  }
}
Enter fullscreen mode Exit fullscreen mode

Inside update, we replace filter with an O(1) swap-remove. When a particle dies, we move the last active particle into its slot and call this.active.pop().

Iterating backward from length - 1 down to 0 keeps the loop safe: the element swapped into index i came from the end of the array, which we already checked, so no particle gets skipped or updated twice. The per-frame array allocation from filter is gone, and active reuses its backing storage across frames.

In my first prototype of this pool, I forgot to reset vy inside reset. It seemed harmless because burst() assigned fresh velocities anyway. In edge cases where an emitter did not overwrite every coordinate right away, though, recycled particles spawned with their old velocity vectors and shot backward across the screen at supersonic speeds the moment they appeared. It was the same problem as an unemptied shopping cart with someone else's groceries still in the basket.

Always reset every property on release. Leaving stale state on a recycled object leads to bugs that are painful to track down, so we will lock this rule down with a unit test below.

Zero-allocation vectors in the hot path

Factory conveyor illustration titled 240,000 Temporary Vec2s Per Second showing add(a, b) and scale(a, dt) dumping temporary vector objects into a GC bin, contrasted with an in-place out buffer via scaleAndAdd(out, a, b, s).
Pure vector helpers churn 240,000 temporary Vec2 objects per second across 1,000 bodies; writing into an out buffer via scaleAndAdd(out, a, b, s) eliminates the garbage.

Recycling particles fixes the emitter, yet temporary vector calculations often create just as much garbage in the same loop.

In our physics engine, helpers like add, sub, and scale were pure, immutable functions that returned a new object literal every time:

// BEFORE โ€” counter-example from basic vector libraries (pure functions)
export const add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });
export const scale = (a: Vec2, s: number): Vec2 => ({ x: a.x * s, y: a.y * s });
Enter fullscreen mode Exit fullscreen mode

That style reads nicely in normal application code. Inside an integration loop running 60 times a second, it churns through memory fast:

// BEFORE โ€” counter-example: integration with pure functions
b.vel = add(b.vel, scale(gravity, dt)); // 2 new Vec2 objects
b.pos = add(b.pos, scale(b.vel, dt));    // 2 more new Vec2 objects
Enter fullscreen mode Exit fullscreen mode

That is four temporary Vec2 objects per physics body per frame. With 1,000 active bodies, the loop allocates and discards 240,000 tiny objects every second, feeding the same sawtooth curve.

The fix is to switch those hot-path helpers to in-place mutations that write into a caller-supplied out parameter:

// src/vec.ts
export type Vec2 = { x: number; y: number };

export function addInPlace(out: Vec2, a: Vec2, b: Vec2): Vec2 {
  out.x = a.x + b.x;
  out.y = a.y + b.y;
  return out;
}

export function scaleInPlace(out: Vec2, a: Vec2, s: number): Vec2 {
  out.x = a.x * s;
  out.y = a.y * s;
  return out;
}

// out = a + b * s  โ€” exactly the integrator's shape, in a single call
export function scaleAndAdd(out: Vec2, a: Vec2, b: Vec2, s: number): Vec2 {
  out.x = a.x + b.x * s;
  out.y = a.y + b.y * s;
  return out;
}
Enter fullscreen mode Exit fullscreen mode

Because out can be the same object as a, calling scaleAndAdd(b.vel, b.vel, gravity, dt) updates b.vel in place and drops all four allocations per body to zero:

// AFTER โ€” in-place integration pattern
scaleAndAdd(b.vel, b.vel, gravity, dt); // vel += gravity * dt (0 allocations)
scaleAndAdd(b.pos, b.pos, b.vel, dt);    // pos += vel     * dt (0 allocations)
Enter fullscreen mode Exit fullscreen mode

When an intermediate step genuinely needs temporary storage, allocate a single static scratch buffer once outside the loop:

// src/vec.ts (continued)
const scratch: Vec2 = { x: 0, y: 0 }; // allocated once, outside the loop

export function reflect(vel: Vec2, normal: Vec2): void {
  const d = 2 * (vel.x * normal.x + vel.y * normal.y);
  scaleInPlace(scratch, normal, d); // scratch = normal * d
  vel.x -= scratch.x;
  vel.y -= scratch.y;
}
Enter fullscreen mode Exit fullscreen mode

In-place mutations do trade readability for speed. add(a, b) is easy to scan; scaleAndAdd(out, a, b, s) takes more attention to read. Keep in-place vectors for verified hot paths that run thousands of times per frame, and stick to pure functions everywhere else.

Measuring the wins: empirical benchmarks

Blueprint tank diagram titled Object Pool Stopped at 347 showing a 347 high-water mark with acquire and release circulation pipes and a gauge stopping at 347 created objects, never creating a 401st object.
Once the pool warms up to the scene's 347-particle high-water mark, allocations flatline and never create a 348th object.

Saying an approach generates less garbage is only a guess until you measure it. To compare both versions fairly, we use a seeded pseudo-random number generator (mulberry32) so both runs spawn identical particle trajectories in the exact same order:

// src/rng.ts
export function makeRng(seed: number): () => number {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6d2b79f5) | 0;
    let t = Math.imul(s ^ (s >>> 15), 1 | s);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
Enter fullscreen mode Exit fullscreen mode
// src/bench.ts
export interface BenchResult {
  allocations: number; // number of Particle objects created
  ms: number;          // total execution time
  survived: number;    // number of particles alive at the end
}
Enter fullscreen mode Exit fullscreen mode

The unpooled baseline counts every object it creates:

// src/bench.ts (baseline)
export function benchBaseline(
  frames: number,
  burstEvery: number,
  burstCount: number,
  seed: number,
): BenchResult {
  const rng = makeRng(seed);
  let particles: Particle[] = [];
  let allocations = 0;
  const dt = 1 / 60;
  const t0 = performance.now();

  for (let f = 0; f < frames; f++) {
    if (f % burstEvery === 0) {
      for (let i = 0; i < burstCount; i++) {
        const a = rng() * Math.PI * 2;
        const speed = 40 + rng() * 150;
        const life = 0.3 + rng() * 0.4;
        particles.push({
          x: 0,
          y: 0,
          vx: Math.cos(a) * speed,
          vy: Math.sin(a) * speed,
          life,
          max: life,
        });
        allocations++;
      }
    }
    for (const p of particles) {
      p.life -= dt;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.vy += 220 * dt;
    }
    particles = particles.filter((p) => p.life > 0); // + 1 array allocation per frame
  }

  return {
    allocations,
    ms: performance.now() - t0,
    survived: particles.length,
  };
}
Enter fullscreen mode Exit fullscreen mode

The pooled version runs the same simulation through ParticleSystem and reads the allocation count from the pool:

// src/bench.ts (pooled)
export function benchPooled(
  frames: number,
  burstEvery: number,
  burstCount: number,
  seed: number,
): BenchResult {
  const rng = makeRng(seed);
  const sys = new ParticleSystem(0);
  const dt = 1 / 60;
  const t0 = performance.now();

  for (let f = 0; f < frames; f++) {
    if (f % burstEvery === 0) sys.burst(0, 0, burstCount, rng);
    sys.update(dt);
  }

  return {
    allocations: sys.allocations,
    ms: performance.now() - t0,
    survived: sys.activeCount,
  };
}
Enter fullscreen mode Exit fullscreen mode

First, a heavy scenario: 3,600 frames (60 seconds at 60 FPS), spawning 60 particles every 6 frames with seed = 42:

========================================================
  Object Pool Benchmark โ€” pooled vs unpooled particles
========================================================

### Heavy scenario
(frames=3600, burstEvery=6, burstCount=60, seed=42)

| Metric                     | Unpooled |  Pooled |
|----------------------------|----------|---------|
| Objects created            |   36,000 |     347 |
| Array allocs (per frame)   |    3,600 |       0 |
| Time (ms, median/5 runs)   |    13.38 |    5.49 |
| Survived (final count)     |      279 |     279 |
Enter fullscreen mode Exit fullscreen mode

The allocation counts are deterministic across machines. The unpooled version creates 3,600 / 6 ร— 60 = 36,000 particle objects. The pooled version creates 347 objects (its high-water mark) and stops allocating, cutting object creation by two orders of magnitude.

Per-frame array allocations drop from 3,600 to zero, and the survived count matches (279 = 279), confirming both runs simulated the exact same particles.

Raw CPU time also drops from 13.38 ms to 5.49 ms, and cutting out the garbage removes the unpredictable 15 to 30 ms GC spikes that make a game hitch. A smooth game depends on a steady 99th-percentile frame time, even more than a high average framerate.

When an object pool is useless

An object pool is not a magic wand, and anyone telling you to pool everything is overselling it.

Modern JavaScript engines like V8 use generational garbage collection. Newly allocated objects land in the young generation (the Nursery), where a lightweight scavenger sweeps them in under a millisecond. When an object is allocated, used briefly, and discarded right away, V8 handles it with very little overhead.

Under low allocation rates, a pool adds extra code and bookkeeping for no real gain. Here is a light workload: 600 frames (10 seconds), spawning 8 particles once every 60 frames (1 second):

### Light scenario (pooling unnecessary)
(frames=600, burstEvery=60, burstCount=8, seed=42)

| Metric                     | Unpooled |  Pooled |
|----------------------------|----------|---------|
| Objects created            |       80 |       8 |
| Array allocs (per frame)   |      600 |       0 |
| Time (ms, median/5 runs)   |     0.02 |    0.01 |
| Survived (final count)     |        0 |       0 |
Enter fullscreen mode Exit fullscreen mode

Object creation drops from 80 to 8, yet the 0.02 ms vs 0.01 ms timing difference is pure measurement noise. Depending on CPU cache locality and function inlining, the overhead of acquire(), release(), and reset() can even make a pooled version slightly slower than V8's scavenger.

Allocating 80 objects over 10 seconds does not bother V8 at all. Building an object pool for that is like setting up a coin-locked cart corral and hiring a cart crew for a corner bodega where people walk in for a loaf of bread.

Use an object pool when your per-frame hot path allocates hundreds or thousands of short-to-medium-lived objects per second (particles, bullets, collision manifolds, network packets, vector buffers) and Chrome DevTools shows a sawtooth heap curve with GC pauses. Skip it when allocations are sporadic, counts are small, or objects live for a long time. If the heap timeline is already flat, pooling is premature optimization.

Automated Vitest verification

A broken pool usually fails in one of two ways:

  1. Handing the same object to two active callers at once (shared state mutation).
  2. Returning an object without resetting its fields (ghost bugs).

We can lock down these invariants in Vitest:

// test/pool.test.ts
import { describe, it, expect } from "vitest";
import { Pool } from "../src/pool";

interface Box {
  value: number;
}

function makePool(initial = 0) {
  return new Pool<Box>({
    initial,
    create: () => ({ value: 0 }),
    reset: (b) => {
      b.value = 0;
    },
  });
}

describe("Pool", () => {
  it("hands out a different object on each consecutive acquire", () => {
    const pool = makePool();
    const a = pool.acquire();
    const b = pool.acquire();
    expect(a).not.toBe(b); // never hand the same cart to two shoppers
  });

  it("returns a released object on the next acquire", () => {
    const pool = makePool();
    const a = pool.acquire();
    pool.release(a);
    const b = pool.acquire();
    expect(b).toBe(a); // same object, back in the bay and handed out again
  });

  it("resets an object on release (no leftover state)", () => {
    const pool = makePool();
    const a = pool.acquire();
    a.value = 42;
    pool.release(a);
    const b = pool.acquire();
    expect(b.value).toBe(0); // no leftover items from the previous shopper
  });

  it("grows up to the high-water mark, then stops creating", () => {
    const pool = makePool();
    const a = pool.acquire();
    const b = pool.acquire();
    const c = pool.acquire();
    expect(pool.created).toBe(3);

    pool.release(a);
    pool.release(b);
    pool.release(c);

    // take all three back: they must all come from the bay, with no new creation
    pool.acquire();
    pool.acquire();
    pool.acquire();
    expect(pool.created).toBe(3); // the water level stays put
  });
});
Enter fullscreen mode Exit fullscreen mode

Because free is a LIFO array backed by pop() and push(), consecutive release and acquire calls are deterministic. The last test verifies the high-water mark: three objects in concurrent use push created to 3, and releasing then re-acquiring them leaves created at 3.

Next, we test ParticleSystem end to end to confirm that expired particles go back to the pool and get reused on the next burst:

// test/particle-system.test.ts
import { describe, it, expect } from "vitest";
import { ParticleSystem } from "../src/particle-system";
import { makeRng } from "../src/rng";

describe("ParticleSystem", () => {
  it("returns a dead particle to the pool and reuses it", () => {
    const sys = new ParticleSystem(0);
    const rng = makeRng(1);

    sys.burst(0, 0, 10, rng);
    expect(sys.activeCount).toBe(10);
    expect(sys.allocations).toBe(10); // the first 10 really were created

    sys.update(100); // a huge dt: every particle's life drops below zero
    expect(sys.activeCount).toBe(0); // all of them went back to the pool

    sys.burst(0, 0, 10, rng);
    expect(sys.allocations).toBe(10); // still 10: NO new allocation, they came from the bay
  });
});
Enter fullscreen mode Exit fullscreen mode

The second burst triggers zero new heap allocations. Ten carts went out, came back, got emptied, and went right back into circulation.

Finally, we verify that scaleAndAdd returns the exact buffer reference passed as out:

// test/vec.test.ts
import { describe, it, expect } from "vitest";
import { scaleAndAdd } from "../src/vec";

describe("vec (in-place)", () => {
  it("updates out in place without creating a new object", () => {
    const out = { x: 0, y: 0 };
    const pos = { x: 1, y: 2 };
    const vel = { x: 0, y: 10 };
    const r = scaleAndAdd(out, pos, vel, 0.5); // out = pos + vel * 0.5

    expect(r).toBe(out); // the returned value is the very buffer we passed in
    expect(out).toEqual({ x: 1, y: 7 });
  });
});
Enter fullscreen mode Exit fullscreen mode

expect(r).toBe(out) confirms no new object was allocated. Across thousands of entities running at 60 FPS, keeping that contract intact prevents GC stutter.

Summary

  • Naive push({...}) and filter(...) loops pay twice: they allocate every spawned object and allocate a replacement array on every frame.
  • Check the JS Heap track in Chrome DevTools Performance; repeated climbs followed by vertical drops point to allocation churn and stop-the-world GC pauses.
  • In Pool<T>, acquire() hands out recycled instances from the return bay and release() resets and restocks them.
  • A pool only allocates up to your game's peak concurrency (the high-water mark), then stops allocating.
  • Replace filter() with O(1) swap-remove by copying the last item into the dead slot, calling pop(), and looping backward.
  • On intensive physics loops, swap immutable math helpers (add, scale) for in-place operations (scaleAndAdd(out, a, b, s)) and static scratch buffers.
  • Reset every field in reset on release so recycled objects never carry stale velocities or positions.
  • Profile before adding a pool. Generational GC handles small, short-lived allocations cheaply, so only pool when you see actual GC pressure.

Source code and live demo

The full source code (pool implementation, particle system, in-place vector math, benchmark CLI, and test suite) is open source on GitHub:

GitHub Repository: github.com/m2-md/object-pools-zero-allocation

Interactive Live Demo: m2-md.github.io/object-pools-zero-allocation

Run npm test to verify the contracts and npm run bench to reproduce the benchmark numbers on your own hardware.

Fast game loops come from knowing what the runtime allocates behind the scenes and cutting waste where it actually hurts. Keep the carts rolling back into the bay, and the exit stays clear.

Canvas 2D and game architecture series

โšก Want the bundled TypeScript 2D Canvas Starter Kit & Cheatsheets? Grab the TS 2D Canvas Physics & HiDPI Starter Kit on Buy Me a Coffee.

About the author

Hi! I'm Mustafa Morbel, a software engineer with over 17 years of experience building web technologies, game architectures, browser rendering engines, and AI workflows.

You can inspect all codebases, runnable demos, and test suites on my GitHub profile.

For new technical guides and architecture posts, connect with me on LinkedIn and X / Twitter (@mustafamorbel).

Have you wrestled with garbage collection pauses or written custom pooling strategies in your web games? I'd love to hear your thoughts in the comments below.

Top comments (0)