HTML5 game publishing

three.js Dispose: Stopping GPU Memory Leaks Between Levels

What needs dispose(), a safe traversal helper, sharing assets, reading renderer.info, lost WebGL contexts and a level-unload checklist.

PlayKovo Team4 min read
Games currently available on PlayKovo. Open a title to see its current listing.

Three.js makes 3D in the browser approachable, and it hides a trap that catches nearly everyone: JavaScript's garbage collector does not clean up GPU memory. Create a mesh, give it a geometry and a texture, remove it from the scene, and the objects in JavaScript are collectable, but the buffers and textures on the graphics card stay until you explicitly dispose of them. A game that loads a new level every few minutes quietly fills video memory until a phone tab crashes. This post explains what to dispose, how, and how to check that you did it.

What lives on the GPU

In three.js, these objects hold GPU resources and need an explicit dispose() call when you are done with them:

  • BufferGeometry: vertex and index buffers.
  • Material: shader programs (shared, so they are reference-counted internally) and any uniforms that hold textures.
  • Texture: image data uploaded to the GPU.
  • WebGLRenderTarget: off-screen framebuffers, used by post-processing and shadows.
  • Instanced attributes and skeleton textures for skinned meshes.

The scene graph itself (Object3D, Group) is plain JavaScript and does not need disposal.

A disposal helper

Removing a mesh from its parent is not enough. Walk the tree and dispose what is inside:

function disposeObject(root) {
  root.traverse(obj => {
    if (obj.geometry) obj.geometry.dispose();
    const mats = Array.isArray(obj.material) ? obj.material : obj.material ? [obj.material] : [];
    for (const m of mats) {
      for (const key in m) {
        const v = m[key];
        if (v && v.isTexture) v.dispose();
      }
      m.dispose();
    }
  });
  root.removeFromParent();
}

Two cautions. First, do not dispose of resources that other objects still use. If twenty trees share one geometry and one material, disposing when you remove a single tree breaks the other nineteen. Either track references yourself or dispose shared assets only when the whole level is torn down. Second, textures loaded once and reused across levels should be kept in a cache and disposed deliberately.

Share assets instead of cloning

The cheapest dispose is the one you never need. Create one geometry and one material per kind of object and reuse them:

const treeGeo = new THREE.ConeGeometry(1, 3, 6);
const treeMat = new THREE.MeshLambertMaterial({ color: 0x2e7d32 });
for (const p of treePositions) {
  const m = new THREE.Mesh(treeGeo, treeMat);
  m.position.copy(p);
  scene.add(m);
}

For hundreds of the same object, use InstancedMesh, which draws all of them in one call and keeps a single geometry. Fewer draw calls also make a bigger difference on phones than almost any other optimization. Cloning a mesh with clone() shares the geometry and material by default, which is good, but cloning a material with material.clone() creates a new one that will need disposal.

Check what is leaking

The renderer keeps counters of what exists on the GPU:

console.log(renderer.info.memory);   // { geometries: n, textures: n }
console.log(renderer.info.render);   // { calls, triangles, ... }

Print these after loading a level, after unloading it and after loading it again. If geometries and textures keep climbing level after level, something is not being disposed. A simple automated check is a debug command that loads and unloads a level twenty times and asserts that the counts return to where they started. Pair it with the heap snapshot in the browser's DevTools Memory panel to catch JavaScript-side leaks, such as event listeners and arrays that still reference removed objects. See garbage collection and memory leaks in JavaScript games.

Lost contexts

Mobile browsers can drop the WebGL context, for example when the tab is in the background and memory is tight. Listen for it:

canvas.addEventListener('webglcontextlost', e => { e.preventDefault(); pauseGame(); });
canvas.addEventListener('webglcontextrestored', () => { rebuildGpuResources(); resumeGame(); });

Three.js handles part of the restoration, but anything you created manually, such as render targets and custom buffers, needs your own recreate step. At minimum, show a message and offer to reload instead of a black canvas. The patterns in error handling in HTML5 games apply.

Cut memory use at the source

  • Texture size. A 2048 by 2048 RGBA texture is 16 MB uncompressed on the GPU, regardless of how small the file is. Mipmaps add about a third. Use the smallest size that looks right, and avoid big textures for small objects.
  • Use texture atlases. Fewer, larger textures instead of many tiny ones. See sprite atlases for HTML5 games.
  • Limit the pixel ratio. renderer.setPixelRatio(Math.min(devicePixelRatio, 2)) avoids rendering at 3x on high-density phones.
  • Lower shadow map sizes and disable shadows where they are not visible.
  • Merge static geometry that never moves.

A level-unload checklist

  1. Stop the animation loop for the level, and cancel pending loads.
  2. Dispose every geometry, material and texture the level owns.
  3. Dispose render targets and post-processing passes.
  4. Remove event listeners and clear arrays that reference level objects.
  5. Check renderer.info.memory.

For the player-facing symptoms, such as lag and crashes on lower-end devices, see fixing lag in browser games, and for a look at what 3D browser games are doing in practice, the best 3D browser games.

We use optional cookies for site analytics and site advertising. You can change your choice later. Privacy policy.