IntelInlet
Studio journal
Canvas game engineering / / 2 min read

A Canvas 2D particle pool with an allocation-free update loop for 144 Hz

Use fixed typed arrays, swap removal and an explicit overflow policy, then measure allocation during a repeatable burst.

Clicking ore sprays fragments for 0.4 seconds. At a steady 600 spawns per second about 240 remain alive, but bursts can exceed that. Try 512 slots and record both peak occupancy and dropped requests before choosing a final capacity.

Procedure

  1. Store position, velocity and remaining life in separate fixed-length arrays. A live count defines the active prefix. Spawn into the next slot. When full, drop a decorative particle. Keep reward accounting separate so an overloaded effect never costs the player currency.

  2. When life expires, copy the last live slot over the dead one. Keep the loop index unchanged to process the moved particle. Copy every field you add. This minimal example uses one dimension; add y and vertical velocity for a screen effect.

  3. After initialization and asset loading, record the same ten-second click sequence. Compare the pool with an object array rebuilt using filter. Inspect allocation samples, GC events and the longest frames. Turn off per-frame string logging during both runs.

const capacity = 512;
const x = new Float32Array(capacity);
const vx = new Float32Array(capacity);
const life = new Float32Array(capacity);
let live = 0;
function spawn(start, speed) {
  if (live === capacity) return false;
  x[live] = start; vx[live] = speed; life[live] = 0.4;
  live++;
  return true;
}
function update(dt) {
  for (let i = 0; i < live;) {
    life[i] -= dt;
    if (life[i] <= 0) {
      const last = --live;
      x[i] = x[last]; vx[i] = vx[last]; life[i] = life[last];
    } else {
      x[i] += vx[i] * dt;
      i++;
    }
  }
}

Choosing an approach

Removal Advantage Cost
Swap with last Dense iteration, constant-time removal Indices move
Free-slot stack Stable slots Needs an active set or scan
Per-frame filter Simple predicate Builds new arrays

Check the result

Set capacity to two and request three particles. The third spawn should fail explicitly. Expire the first and check that the moved particle updates exactly once. Allocation-free here describes the update loop. Browser work, drawing and the rest of the game still need profiling before claiming an overall frame rate.

After reducing allocation, use the drawing and DPR experiments to locate remaining long frames.

Frequently asked questions

Can an array index be a long-lived entity ID?

Swap removal moves it. Use stable IDs with a location map, or fixed slots with generation numbers.

Why does a pooled effect still stutter?

Inspect painting, asset sizes, unrelated scripts and GC events. Attribute a win to the pool only when allocation and the observed long frames improve together.

References

Related reading

Chibi arcade ↗