TExcelTAD
Home › 2D Games with JavaScript & Canvas › Shooter 4: Object Pooling

Shooter 4: Object Pooling

The shooter creates a new object for every bullet, every enemy and (in this step) every spark of an explosion, then throws it away a second later. JavaScript's garbage collector (GC) cleans up the thrown-away objects for you, but it does that work in bursts. In a game, a burst of a few milliseconds at the wrong moment shows up as a stutter: a frame that arrives late.

Object pooling avoids the churn: keep dead objects in a "free list" and reuse them instead of allocating new ones. This lesson builds a small Pool class, measures how much allocation it saves, and switches the shooter to pools.

Note: Pool because measurements tell you to, not by default. Modern engines (V8, SpiderMonkey) are very good at short-lived objects, and a game with a few hundred objects rarely needs pooling. Particle systems, bullet-hell games and low-end phones are where it pays off.

A small pool

js
class Pool {
  constructor(create) {
    this.create = create;    // makes a brand-new object (only when the free list is empty)
    this.live = [];          // objects in use, updated and drawn every frame
    this.free = [];          // dead objects waiting to be reused
    this.created = 0;        // how many objects were ever allocated
  }
  acquire() {
    let obj = this.free.pop();
    if (!obj) { obj = this.create(); this.created++; }
    this.live.push(obj);
    return obj;
  }
  releaseAt(i) {             // swap-remove: O(1), order doesn't matter
    const obj = this.live[i];
    const last = this.live.pop();
    if (i < this.live.length) this.live[i] = last;
    this.free.push(obj);
  }
}

Two details matter:

  • releaseAt swaps instead of splicing. splice shifts every later element down; swap-remove moves just one. Loop backwards when releasing, so the element moved into slot i has already been visited.
  • The caller sets every field after acquire(). A reused bullet still holds its old position, velocity and life. Forgetting to set one field is the classic pooling bug: a bullet that spawns already "dead", or with last round's speed.

Measuring it

Here is the same bullet stream simulated twice for 10 seconds at 60 updates per second: one bullet every 6 frames, each living 60 frames. The first version allocates with an object literal and filters the array every frame (as in Shooter 2, which used splice); the second uses the pool. A counter records every object and array created.

js · try it yourself
class Pool {
  constructor(create) { this.create = create; this.live = []; this.free = []; this.created = 0; }
  acquire() {
    let obj = this.free.pop();
    if (!obj) { obj = this.create(); this.created++; }
    this.live.push(obj);
    return obj;
  }
  releaseAt(i) {
    const obj = this.live[i];
    const last = this.live.pop();
    if (i < this.live.length) this.live[i] = last;
    this.free.push(obj);
  }
}

const FRAMES = 600, FIRE_EVERY = 6, LIFE = 60;

function withoutPool() {
  let bullets = [], objects = 0, arrays = 0, maxLive = 0;
  for (let f = 0; f < FRAMES; f++) {
    if (f % FIRE_EVERY === 0) { bullets.push({ x: 0, vx: 6, life: LIFE }); objects++; }
    for (const b of bullets) { b.x += b.vx; b.life--; }
    bullets = bullets.filter((b) => b.life > 0); arrays++;   // a new array every frame
    maxLive = Math.max(maxLive, bullets.length);
  }
  return { objects, arrays, maxLive, liveAtEnd: bullets.length };
}

function withPool() {
  const pool = new Pool(() => ({ x: 0, vx: 0, life: 0 }));
  let maxLive = 0;
  for (let f = 0; f < FRAMES; f++) {
    if (f % FIRE_EVERY === 0) { const b = pool.acquire(); b.x = 0; b.vx = 6; b.life = LIFE; }
    for (let i = pool.live.length - 1; i >= 0; i--) {
      const b = pool.live[i];
      b.x += b.vx; b.life--;
      if (b.life <= 0) pool.releaseAt(i);
    }
    maxLive = Math.max(maxLive, pool.live.length);
  }
  return { objects: pool.created, arrays: 0, maxLive, liveAtEnd: pool.live.length };
}

console.log('without pool:', withoutPool());
console.log('with pool:   ', withPool());
without pool: { objects: 100, arrays: 600, maxLive: 10, liveAtEnd: 9 }
with pool:    { objects: 10, arrays: 0, maxLive: 10, liveAtEnd: 9 }

Both versions behave identically (same peak and same bullets alive at the end), but the pool allocates only as many bullets as were ever alive at the same time. After the first second it allocates nothing at all, however long the game runs. The unpooled version keeps allocating forever: 10 bullets and 60 arrays every second.

Counting allocations is a deterministic stand-in for the real measurement. In the browser, check with DevTools:

Tool What to look for
Performance panel, record 10 s of play "Minor GC" blocks inside frames that went over budget
Memory panel, Allocation instrumentation on timeline blue bars that keep appearing while you play: something allocates every frame
A frame-time graph like the one in Debugging & Performance regular spikes every second or two while nothing special happens in the game
Memory panel heap size (or Task Manager) during long play a saw-tooth: memory climbs steadily, then drops at each collection

Step 4: the pooled shooter

The game now uses three pools: bullets, enemies and sparks, a small particle burst whenever an enemy is hit or destroyed. Sparks are exactly the kind of object pools exist for: dozens are created per second and each lives a fraction of a second. The HUD shows live objects, objects waiting in the free lists, and the total ever allocated. Play for a while and watch created stop growing.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

class Pool {
  constructor(create) { this.create = create; this.live = []; this.free = []; this.created = 0; }
  acquire() {
    let obj = this.free.pop();
    if (!obj) { obj = this.create(); this.created++; }
    this.live.push(obj);
    return obj;
  }
  releaseAt(i) {
    const obj = this.live[i];
    const last = this.live.pop();
    if (i < this.live.length) this.live[i] = last;
    this.free.push(obj);
  }
  releaseAll() { while (this.live.length) this.free.push(this.live.pop()); }
}

const BULLET_SPEED = 360, BULLET_LIFE = 0.9, FIRE_DELAY = 0.1, IFRAMES = 1.0;
const bullets = new Pool(() => ({ x: 0, y: 0, vx: 0, vy: 0, life: 0 }));
const enemies = new Pool(() => ({ x: 0, y: 0, r: 0, speed: 0, hp: 0, maxHp: 0, color: '', points: 0, flash: 0 }));
const sparks = new Pool(() => ({ x: 0, y: 0, vx: 0, vy: 0, life: 0, color: '' }));
const mouse = { x: W / 2 + 80, y: H / 2, down: false };
const player = { x: 0, y: 0, r: 11, speed: 140, angle: 0, hp: 0, invuln: 0 };
let fireTimer, spawnTimer, time, score, over;

function reset() {
  Object.assign(player, { x: W / 2, y: H / 2, angle: 0, hp: 5, invuln: 0 });
  bullets.releaseAll(); enemies.releaseAll(); sparks.releaseAll();   // back to the free lists, not thrown away
  fireTimer = 0; spawnTimer = 1; time = 0; score = 0; over = false;
}
reset();

cv.addEventListener('pointermove', (e) => {
  const r = cv.getBoundingClientRect();
  mouse.x = (e.clientX - r.left) * W / r.width;
  mouse.y = (e.clientY - r.top) * H / r.height;
});
cv.addEventListener('pointerdown', (e) => { if (e.button === 0) mouse.down = true; });
addEventListener('pointerup', () => { mouse.down = false; });
cv.addEventListener('blur', () => { mouse.down = false; });

const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const spawnDelay = (t) => Math.max(0.35, 1.4 - t * 0.04);

function spawnEnemy() {
  const side = Math.floor(Math.random() * 4), m = 16;
  const e = enemies.acquire();                        // set EVERY field: the object may be reused
  e.x = side === 1 ? W + m : side === 3 ? -m : Math.random() * W;
  e.y = side === 0 ? -m : side === 2 ? H + m : Math.random() * H;
  const big = Math.random() < 0.15;
  e.r = big ? 15 : 9; e.speed = big ? 38 : 62 + time;
  e.hp = e.maxHp = big ? 6 : 2;
  e.color = big ? '#ab47bc' : '#ef5350'; e.points = big ? 50 : 10; e.flash = 0;
}

function burst(x, y, n, color) {
  for (let k = 0; k < n; k++) {
    const s = sparks.acquire();
    const a = Math.random() * Math.PI * 2, v = 40 + Math.random() * 120;
    s.x = x; s.y = y; s.vx = Math.cos(a) * v; s.vy = Math.sin(a) * v;
    s.life = 0.2 + Math.random() * 0.3; s.color = color;
  }
}

function fire() {
  const b = bullets.acquire();
  const cos = Math.cos(player.angle), sin = Math.sin(player.angle);
  b.x = player.x + cos * 14; b.y = player.y + sin * 14;
  b.vx = cos * BULLET_SPEED; b.vy = sin * BULLET_SPEED; b.life = BULLET_LIFE;
}

function update(dt) {
  if (over) { if (pressed.has('KeyR')) reset(); return; }
  time += dt;

  let dx = 0, dy = 0;
  if (keys.has('KeyA') || keys.has('ArrowLeft')) dx -= 1;
  if (keys.has('KeyD') || keys.has('ArrowRight')) dx += 1;
  if (keys.has('KeyW') || keys.has('ArrowUp')) dy -= 1;
  if (keys.has('KeyS') || keys.has('ArrowDown')) dy += 1;
  const len = Math.hypot(dx, dy);
  if (len > 0) { dx /= len; dy /= len; }
  player.x = clamp(player.x + dx * player.speed * dt, player.r, W - player.r);
  player.y = clamp(player.y + dy * player.speed * dt, player.r, H - player.r);
  player.angle = Math.atan2(mouse.y - player.y, mouse.x - player.x);
  player.invuln = Math.max(0, player.invuln - dt);

  if (mouse.down || keys.has('Space')) {
    fireTimer -= dt;
    if (fireTimer <= 0) { fire(); fireTimer += FIRE_DELAY; }
  } else fireTimer = Math.max(fireTimer - dt, 0);

  spawnTimer -= dt;
  while (spawnTimer <= 0) { spawnEnemy(); spawnTimer += spawnDelay(time); }

  const bl = bullets.live;
  for (let i = bl.length - 1; i >= 0; i--) {
    const b = bl[i];
    b.x += b.vx * dt; b.y += b.vy * dt; b.life -= dt;
    if (b.life <= 0 || b.x < -10 || b.x > W + 10 || b.y < -10 || b.y > H + 10) bullets.releaseAt(i);
  }

  const el = enemies.live;
  for (let i = el.length - 1; i >= 0; i--) {
    const e = el[i];
    const ex = player.x - e.x, ey = player.y - e.y, d = Math.hypot(ex, ey) || 1;
    e.x += (ex / d) * e.speed * dt;
    e.y += (ey / d) * e.speed * dt;
    for (let j = bl.length - 1; j >= 0; j--) {
      const b = bl[j];
      if (Math.hypot(b.x - e.x, b.y - e.y) < e.r + 2) {
        bullets.releaseAt(j);
        e.hp -= 1; e.flash = 0.06;
        burst(b.x, b.y, 3, '#ffee58');
        break;
      }
    }
    e.flash = Math.max(0, e.flash - dt);
    if (e.hp <= 0) { score += e.points; burst(e.x, e.y, e.r > 10 ? 30 : 14, e.color); enemies.releaseAt(i); continue; }
    if (d < e.r + player.r && player.invuln === 0) {
      player.hp -= 1; player.invuln = IFRAMES;
      player.x = clamp(player.x + (ex / d) * 24, player.r, W - player.r);
      player.y = clamp(player.y + (ey / d) * 24, player.r, H - player.r);
      burst(player.x, player.y, 20, '#4dd0e1');
      if (player.hp <= 0) over = true;
    }
  }

  const sl = sparks.live;
  for (let i = sl.length - 1; i >= 0; i--) {
    const s = sl[i];
    s.x += s.vx * dt; s.y += s.vy * dt;
    s.vx *= 0.92; s.vy *= 0.92;                           // drag
    s.life -= dt;
    if (s.life <= 0) sparks.releaseAt(i);
  }
}

function drawShip(x, y, angle) {
  ctx.save();
  ctx.translate(Math.round(x), Math.round(y));
  ctx.rotate(angle);
  ctx.fillStyle = '#4dd0e1';
  ctx.beginPath();
  ctx.moveTo(14, 0); ctx.lineTo(-9, -9); ctx.lineTo(-5, 0); ctx.lineTo(-9, 9);
  ctx.closePath(); ctx.fill();
  ctx.fillStyle = '#e0f7fa'; ctx.fillRect(2, -2, 10, 4);
  ctx.restore();
}

function draw() {
  ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
  ctx.strokeStyle = '#1b2030';
  for (let x = 0; x <= W; x += 30) { ctx.beginPath(); ctx.moveTo(x + 0.5, 0); ctx.lineTo(x + 0.5, H); ctx.stroke(); }
  for (let y = 0; y <= H; y += 30) { ctx.beginPath(); ctx.moveTo(0, y + 0.5); ctx.lineTo(W, y + 0.5); ctx.stroke(); }

  for (const s of sparks.live) {
    ctx.globalAlpha = Math.min(1, s.life * 4);
    ctx.fillStyle = s.color;
    ctx.fillRect(Math.round(s.x) - 1, Math.round(s.y) - 1, 2, 2);
  }
  ctx.globalAlpha = 1;
  for (const e of enemies.live) {
    const x = Math.round(e.x), y = Math.round(e.y);
    ctx.fillStyle = e.flash > 0 ? '#fff' : e.color;
    ctx.beginPath(); ctx.arc(x, y, e.r, 0, Math.PI * 2); ctx.fill();
    if (e.maxHp > 2) {
      ctx.fillStyle = '#333'; ctx.fillRect(x - 12, y - e.r - 7, 24, 3);
      ctx.fillStyle = '#66bb6a'; ctx.fillRect(x - 12, y - e.r - 7, Math.round(24 * e.hp / e.maxHp), 3);
    }
  }
  ctx.fillStyle = '#ffee58';
  for (const b of bullets.live) ctx.fillRect(Math.round(b.x) - 2, Math.round(b.y) - 2, 4, 4);
  const blink = player.invuln > 0 && Math.floor(player.invuln * 12) % 2 === 0;
  if (!blink) drawShip(player.x, player.y, player.angle);

  ctx.font = '14px system-ui, sans-serif'; ctx.textAlign = 'left';
  ctx.fillStyle = '#ff5252'; ctx.fillText('♥'.repeat(Math.max(0, player.hp)), 8, 18);
  ctx.fillStyle = '#e0e0e0'; ctx.textAlign = 'right'; ctx.fillText(`score ${score}`, W - 8, 18);
  ctx.font = '11px ui-monospace, monospace'; ctx.textAlign = 'left'; ctx.fillStyle = '#9aa4c0';
  let y = H - 34;
  for (const [name, p] of [['bullets', bullets], ['enemies', enemies], ['sparks', sparks]]) {
    ctx.fillText(`${name.padEnd(8)} live ${String(p.live.length).padStart(3)}  free ${String(p.free.length).padStart(3)}  created ${p.created}`, 8, y);
    y += 12;
  }
  if (over) banner('Game over', `score ${score} - press R to play again`);
}

run(update, draw, 'WASD to move, mouse to aim, hold Space or click to fire');
</script>

What changed from step 3:

  • All three arrays became pools, and every push({...}) became acquire() followed by setting each field. Every splice became releaseAt.
  • reset() releases everything back to the free lists. After a restart, the next round reuses the objects of the previous one.
  • Sparks use the same pattern as bullets plus drag (vx *= 0.92), which makes bursts slow down and look softer. You'll do much more with particles in the Particles lesson.

Tip: Use a pool when objects are created and destroyed many times per second and all have the same shape. Keep the shape fixed: create every property in the create function, even if it starts as 0 or ''. Objects with the same properties in the same order let the JavaScript engine optimize property access.

Test yourself

What problem does object pooling address in games?

  1. Drawing too many pixels
  2. Garbage-collection pauses caused by creating and discarding many short-lived objects
  3. Keyboard input lag
  4. Bullets passing through walls

After const b = bullets.acquire(), why must you set every field of b?

  1. acquire returns undefined
  2. A reused object still holds the values from its previous life
  3. JavaScript objects are read-only
  4. It makes the bullet faster

In the measurement, how many bullet objects does the pooled version allocate?

  1. One per shot (100)
  2. As many as were ever alive at the same time
  3. Zero
  4. One per frame (600)