Capítulo 819 de 859

Chapter 819: How to Dispose of Objects (Manual)

Core Idea

Authoritative rules for when and how to free three.js's underlying GPU resources (buffers, shader programs, textures, framebuffers) via each class's own dispose() method, since three.js has no way to know an object's lifetime on its own.

Key Concepts

  • BufferGeometry.dispose(): frees the WebGLBuffer created per attribute.
  • Material.dispose(): only actually frees the underlying shader program once every material sharing that program has been disposed, since three.js reuses compiled programs where possible.
  • Texture.dispose(): separate from material disposal, since one texture can be shared by multiple materials; frees the WebGLTexture.
  • ImageBitmap.close(): must be called by the application itself for ImageBitmap-sourced textures — three.js can't auto-close it since the bitmap might still be used elsewhere.
  • WebGLRenderTarget.dispose(): frees its texture plus the associated WebGLFramebuffer/WebGLRenderbuffer.
  • Skeleton.dispose(): frees skeleton resources; only call it once no other skinned mesh shares that skeleton.
  • renderer.info: exposes live counts of cached geometries, textures and programs — useful for spotting leaks.
  • Disposing something still in use: not an error, but can cost a frame of performance (e.g. recompiling a shader) — the exception is Controls and renderer instances, which cannot be used again after dispose().

Key Takeaways

  1. Three.js can't know an object's lifetime on its own — the application must call the right dispose() method itself.
  2. Shader programs, textures and skeletons can be shared across multiple materials/meshes, so they're only truly freed once nothing references them anymore.
  3. Disposing a resource that's technically still in use doesn't throw — worst case is a one-frame performance hit — except Controls and renderer instances, which become unusable after dispose().
  4. renderer.info reports live cached-object counts, a practical way to check for leaks.
  5. A common pattern is disposing at natural boundaries (e.g. level transitions) rather than continuously.

Connects To

  • BufferGeometry: the type whose per-attribute buffers this chapter explains how to free.
  • Cleanup (manual): the earlier manual chapter's ResourceTracker pattern automates calling these same dispose() methods across a loaded object hierarchy.