When to dispose: How to completely clean up a Three.js scene

Alright, the following is what I have so far, and I’m doing it to see if there’s any difference in memory use compared to not doing it (my guess is there won’t be and the Garbage Collector will work great, but just in case). Am I missing anything?

console.log('dispose renderer!')
renderer.dispose()

scene.traverse(object => {
	if (!object.isMesh) return
	
	console.log('dispose geometry!')
	object.geometry.dispose()

	if (object.material.isMaterial) {
		cleanMaterial(object.material)
	} else {
		// an array of materials
		for (const material of object.material) cleanMaterial(material)
	}
})

const cleanMaterial = material => {
	console.log('dispose material!')
	material.dispose()

	// dispose textures
	for (const key of Object.keys(material)) {
		const value = material[key]
		if (value && typeof value === 'object' && 'minFilter' in value) {
			console.log('dispose texture!')
			value.dispose()
		}
	}
}

6 Likes