three.js--------内存泄漏处理

【问题描述】
在网页中点击按钮加载模型,点击返回按钮返回,再次点击按钮加载模型重复几次发现内存不断变大,初步认为是内存泄漏
在这里插入图片描述

【解决方案】
最开始时找了网上的有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();
    }
  },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值