In this simple example, I am adding a THREE.SphereGeometry to a THREE.Group and then including the group in the scene. After rendering the scene, my goal is to eliminate the group from the scene and dispose of the geometry.
<html>
<head>
<title>memory-leak-demo-01</title>
<script type='module'>
import * as THREE from '../lib/three-js-129/build/three.module.js';
let canvas = document.createElement('canvas');
let renderer = new THREE.WebGLRenderer({ canvas:canvas, antialias: true });
let camera = new THREE.PerspectiveCamera();
let scene = new THREE.Scene();
scene.add(camera);
function getGroup(){
let group = new THREE.Group();
const geometry = new THREE.SphereGeometry( 5, 8, 8 );
const material = new THREE.MeshBasicMaterial( {color: 0xffff00, wireframe: true} );
group.add(new THREE.Mesh( geometry, material ));
return group;
}
for(let i=0; i<1000; i++){
let myGroup = getGroup();
scene.add(myGroup);
renderer.render(scene, camera);
scene.remove(myGroup);
console.log(`${i} renderer.info.memory: ${JSON.stringify(renderer.info.memory)}`);
}
</script>
</head>
</html>
The issue lies in the fact that even after removing myGroup from the scene, the geometries are not cleared from memory as shown by console logging.
992 renderer.info.memory: {"geometries":993,"textures":0}
993 renderer.info.memory: {"geometries":994,"textures":0}
994 renderer.info.memory: {"geometries":995,"textures":0}
995 renderer.info.memory: {"geometries":996,"textures":0}
996 renderer.info.memory: {"geometries":997,"textures":0}
997 renderer.info.memory: {"geometries":998,"textures":0}
998 renderer.info.memory: {"geometries":999,"textures":0}
999 renderer.info.memory: {"geometries":1000,"textures":0}
I am seeking guidance on how to properly use .dispose() to remove these geometries. My aim is to only dispose of geometries within the group while keeping other objects in the scene intact.
In the actual application I am developing, there are numerous geometries within the group and the group is added and removed from the scene with each requestAnimationFrame cycle. This results in constant memory consumption leading to system slowdowns.
A demo page featuring the above code can be accessed here:
Another page showcasing the same issue but with visible spheres being rendered: