Find memory that grows every time a game restarts, loads a level or opens a menu. Repeat a cycle many times, measure heap after forced garbage collection, event listeners and DOM nodes, and spot steady growth. Includes the usual causes in games (listeners per restart, growing arrays, caches, timers, closures holding old scenes, Web Audio nodes, three.js geometry / textures not disposed, detache...
Download skill (.zip) Files on GitHubGame memory leak detection
Run the check (2D / DOM)
python3 <skill>/scripts/leak-check.py http://localhost:8000/ # default: Enter, then back to title
python3 <skill>/scripts/leak-check.py http://localhost:8000/ --cycle "keys:Enter" --cycle "eval:__game.scenes.switch('title')" --cycles 15
python3 <skill>/scripts/leak-check.py http://localhost:8000/ --cycle "eval:__game.loadLevel(2)" --cycle "eval:__game.loadLevel(1)"
It prints a table of heap (after GC), listeners, DOM nodes and canvases per cycle, ignores the first cycles (warm-up caches), and says LIKELY LEAK if something grows steadily, with the likely cause. Exit code 1 on a leak.
WebGL games: in the viewer’s browser use game-performance-profiling’s perf-probe.js (heap in the console line) while
restarting repeatedly, or renderer.info.memory (geometries, textures) logged after each restart; they must not climb.
Usual causes and fixes
| Grows | Cause | Fix |
|---|---|---|
| Listeners | addEventListener in enter() / start() |
Remove in exit(). Or use an AbortController per scene: { signal }, then abort() |
| Heap | Arrays that only grow (particles, bullets, history, logs) | Pools, cap the length, clear in exit() |
| Heap | Old scenes kept alive (closures in callbacks, global references, event bus listeners) | Unsubscribe; don’t store scenes in globals |
| Heap | setInterval / setTimeout never cleared |
Clear in exit(), or use dt-based timers owned by the scene |
| Heap | Caches keyed by object or string without limits | Limit the size; WeakMap for object keys |
| Audio | New AudioContext per round; <audio> elements created per sound |
One context; buffer sources (they free themselves) |
| GPU (three.js) | Geometries, materials, textures, render targets not disposed | dispose() on level unload; traverse and dispose; reuse instead |
| DOM nodes | HUD elements created per round | Create once, update text |
| Canvases | Offscreen canvases created per frame or round | Create once, reuse |
Finding the exact object (when the cause isn’t obvious)
- Chrome DevTools → Memory → heap snapshot after 1 cycle, then after 10 cycles.
- Compare: sort by “# Delta” / “Size Delta”. Look at your class names (
Enemy,Bullet,PlayScene). - Retainers panel shows what holds them (usually a listener or a global array).
Prove the fix
Run the same leak-check.py command again and show the before/after table. “Listeners: +1 per restart → flat. Heap after
15 restarts: 24 MB → 3.1 MB.”