How to Dispose of WebGLRenderTarget in Three.js

Properly managing GPU memory in Three.js is crucial for maintaining high performance and preventing application crashes, especially when dealing with offscreen rendering. This article explains how to correctly dispose of a WebGLRenderTarget to free up framebuffer, renderbuffer, and texture memory on the GPU, ensuring your WebGL applications remain leak-free.

To free up the GPU memory associated with a WebGLRenderTarget, you must call its .dispose() method. When you call this method, Three.js deallocates the underlying WebGL framebuffer, any associated renderbuffers (like depth or stencil buffers), and the default output texture.

Here is the basic implementation for disposing of a standard render target:

// Initialize the render target
let renderTarget = new THREE.WebGLRenderTarget(width, height);

// ... Use the render target in your render loop ...

// Correctly dispose of the render target to free GPU memory
renderTarget.dispose();

// Release the JavaScript reference to allow garbage collection
renderTarget = null;

Disposing of Custom Depth Textures

If you have manually created and attached a custom depth texture to your render target, calling dispose() on the render target itself will not automatically destroy the depth texture. You must dispose of the depth texture explicitly:

let renderTarget = new THREE.WebGLRenderTarget(width, height);
renderTarget.depthTexture = new THREE.DepthTexture(width, height);

// ...

// Correct disposal sequence
if (renderTarget.depthTexture) {
    renderTarget.depthTexture.dispose();
}
renderTarget.dispose();
renderTarget = null;

Removing References in Materials

Simply disposing of the render target on the GPU is not enough if your JavaScript application still references it. If the render target’s texture (renderTarget.texture) is assigned to a material as a map, you should remove the reference and flag the material for an update:

// Remove texture reference from materials
myMaterial.map = null;
myMaterial.needsUpdate = true;

// Dispose of the target
renderTarget.dispose();
renderTarget = null;

By combining the .dispose() call with manual reference clearing, you ensure that both the WebGL GPU memory and the CPU JavaScript memory are successfully reclaimed.