【问题描述】
在网页中点击按钮加载模型,点击返回按钮返回,再次点击按钮加载模型重复几次发现内存不断变大,初步认为是内存泄漏
【解决方案】
最开始时找了网上的有three.js造成内存泄漏的方法,进行了清除场景中的Group和清除场景,发现内存占用在返回时会减少,但是再次点击加载模型会比第一次更高,最后通过chrome中的开发工具Memory中发现,占用大量内存的是Octree,由于使用的three.js版本没有直接提供 clear 方法来清空八叉树的内容,使用了将八叉树对象重新实例化,以创建新的八叉树替代原有的八叉树。具体代码如下:
// 清除场景
clearScene() {
cancelAnimationFrame(this.animate);
this.scene.traverse((child) => {
if (child.material) {
child.material.dispose();
}
if (child.geometry) {
child.geometry.dispose();
}
child = null;
});
this.renderer.dispose();
this.scene.clear();
this.scene = null;
this.camera = null;
this.controls = null;
this.renderer = null;
},
// 清除组
clearGroup(group) {
const clearCache = (item) => {
if (item.type === "Mesh") {
item.geometry.dispose();
item.material.dispose();
}
};
const removeObj = (obj) => {
let arr = obj.children.filter((x) => !!x);
arr.forEach((item) => {
if (item.children.length) {
removeObj(item);
} else {
clearCache(item);
item.clear();
}
});
obj.clear();
arr = null;
};
removeObj(group);
},
},
beforeDestroy() {
// 在组件销毁前释放八叉树对象
if (this.worldOctree) {
this.worldOctree = new Octree();
}
},