BufferGeometry Resource Disposal and GPU Memory Lifecycle
0 reputation · 31 Jan 2021, 00:11 UTC
0 reputation · 31 Jan 2021, 00:11 UTC
Three.js utilizes BufferGeometry to store vertex data in typed arrays for efficient GPU rendering. While the JavaScript garbage collector manages the CPU-side memory of these objects, the associated WebGL buffers reside in GPU memory and require explicit management.
When removing a Mesh from a scene, the underlying geometry and materials are not automatically released from the GPU. This creates a requirement to call the .dispose() method to prevent memory leaks, particularly in applications that dynamically load and unload large-scale 3D models.
There is uncertainty regarding the most efficient way to track these dependencies when multiple meshes share a single geometry instance. If one mesh is removed but others still reference the geometry, calling dispose prematurely will break the remaining renders.
.dispose() is called only when no active meshes remain?BufferGeometry resources?37275 reputation · 31 Jan 2021, 03:19 UTC
Three.js does not provide built-in reference counting or automatic GPU disposal for shared BufferGeometry instances. Removing a Mesh from a scene leaves the geometry and its WebGL buffers allocated. You must track references manually and call geometry.dispose() only when the last mesh using that geometry is released.
BufferGeometry.dispose() releases the WebGL buffers bound to attributes and the index buffer.Keep a map from geometry instance to active mesh count. Increment when a mesh adopts the geometry, decrement when the mesh is removed, and dispose at zero.
const geometryRefs = new Map();
function retainGeometry(geometry) {
const next = (geometryRefs.get(geometry) ?? 0) + 1;
geometryRefs.set(geometry, next);
return geometry;
}
function releaseGeometry(geometry) {
const current = geometryRefs.get(geometry);
if (!current) return;
const next = current - 1;
if (next <= 0) {
geometryRefs.delete(geometry);
geometry.dispose();
} else {
geometryRefs.set(geometry, next);
}
}
retainGeometry(geometry) when creating each mesh that shares the geometry.releaseGeometry(mesh.geometry).Open Chrome DevTools, go to Memory, and inspect WebGL buffer counts before and after removing the final mesh. The count should drop only when the reference count reaches zero. If buffers remain, check for meshes still referencing the geometry or for missed releaseGeometry calls.
If you are using InstancedMesh, geometries shared across instances follow the same rule: dispose only when the last instance referencing the geometry is released.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.