Updating cloned objects and disposal

Hello - New to three.js. I was just wondering if someone could help on the best practise for updating a scene.
-I’m importing various GLTF model assets and using these to construct a door as a ‘singleDoorGrp’.
-I then have a function that clones the door, currently based on a GUI input to a ‘totalDoorsGrp’
-The user can select between 1 and 5 doors, with the starting default being 4.
-To update the doors on screen, I’m running the following code in the animate() loop.

Is it actually necessary to dispose() or is simply removing and adding back the totalDoorsGrp okay on its own?

if (totalDoorsGrp){
        scene.remove(totalDoorsGrp); 
        totalDoorsGrp.traverse(function (obj) {
            if (obj instanceof THREE.Mesh) {
                obj.geometry.dispose()
                obj.material.dispose();
            }
        });
        totalDoorsGrp = cloneDoors(doorSetup,singleDoorGrp); 
        scene.add(totalDoorsGrp); 
}

Many thanks

Removing a group from the scene (scene.remove(totalDoorsGrp)) simply detaches it from the scene graph, but does not free its geometries or materials from memory. If you don’t call dispose(), the GPU memory (and possibly CPU memory) used by those resources will remain allocated.

If you know for sure you’re not going to reuse those meshes or their materials, you should call dispose() on each mesh’s geometry and material. This ensures three.js can properly clean up and free the memory. On the other hand, if you plan to reuse the same meshes or materials, you might skip calling dispose() and simply remove them from the scene. However, most of the time in a dynamic setup like yours, where you clone the door group and remove old ones, calling dispose() on unused resources is best practice to avoid memory leaks.

2 Likes

Thank you that explains it nicley