I have created a scene using THREEJS that loads GLTF files and image-format tile maps. When I repeatedly destroy and rebuild the scene(ensuring that each destruction removes DOM nodes and all relevant THREEJS objects), I notice that the memory keeps increasing in the Safari browser, but the same code performs normally in the Chrome browser. I have ensured that I properly dispose of all relevant resources when destroying the scene.
The following is the core code of my destruction function:
static disposeObject(object, withMaterial: boolean = true){
const self = this;
const disposeMaterial = (material: Material) => {
Object.getOwnPropertyNames(material).forEach((property: string) => {
const materialProperty = (material)[property];
if (materialProperty !== undefined && materialProperty instanceof Texture) {
const texture = materialProperty;
const image = texture.source.data;
if (image instanceof ImageBitmap) {
console.log('dispose imagebtmap');
image.close();
}else{
console.log('dispose image');
texture.image = null;
}
texture.dispose();
}
});
material.dispose();
};
if (object instanceof Object3D) {
if (object.parent) {
object.parent.remove(object);
object.parent = null;
}
}
if(object.children&&object.children.length>0){
for (let i = object.children.length -1; i >=0 ; i--) {
this.disposeObject(object.children[i]);
}
}
object.children.length = 0;
object.children = null;
if (object.geometry !== undefined) {
object.geometry.dispose();
}
if (object.geometries !== undefined) {
for (const geometry of object.geometries) {
for (const key in geometry.attributes) {
geometry.deleteAttribute(key);
}
geometry.setIndex([]);
geometry.dispose();
}
}
if (object.material !== undefined && withMaterial ) {
if (object.material instanceof Array) {
object.material.forEach((material: Material | undefined) => {
if (material !== undefined) {
disposeMaterial(material);
}
});
} else {
disposeMaterial(object.material);
}
}
for(let key in object.userData){
delete object.userData[key];
}
object.userData = {};
object = undefined;
};
THREEJS Version: r138
Google Chrome Version: 119.0.6045.200
Safari Version: 17.0(19616.1.27.211.1)
Is there anyone who can give me some advice? Thanks!!!