threejs 创建了10w条THREE.Line,销毁数据,等待了10秒

133 阅读1分钟

three + 高德地图,绘制路线,数据量比较大,页面路由切换时,需要把threejs创建的对象销毁。 简单粗暴的方法,直接卡顿几秒才可以切换,体验极差。

默认销毁代码

beforeDestroy(){
    this.roadGroup.children.forEach(item => {
        this.roadGroup.remove(item);
        item.geometry && item.geometry.dispose();
    });
}

此时卡顿的时候,打印了下children的长度接近10w个,销毁占用时间,阻塞了。
想到不耽误销毁数据,又不影响其他进程,那就异步分批销毁,比如每次销毁300个。这样不一直占用主线程,静默销毁数据,解决。

修改后的代码

const destroyRoadGroup = function (callback) {
    if (this.roadGroup) {
        let group = this.roadGroup;

        let index = 0;
        const batchSize = 300; // 每批处理多少个对象
        const delay = 1; // 每批之间延迟时间(ms)

        let children = group.children;
        const disposeBatch = () => {
            const end = Math.min(index + batchSize, children.length);
            for (let i = index; i < end; i++) {
                const obj = children[i];
                if (obj.geometry) {
                    obj.geometry.dispose();
                }
                if (obj.material) {
                    if (Array.isArray(obj.material)) {
                        obj.material.forEach((mat) => mat.dispose());
                    } else {
                        obj.material.dispose();
                    }
                }
            }

            index = end;

            if (index < children.length) {
                setTimeout(disposeBatch, delay); // 下一批
            } else {
                // 所有资源释放完毕
                group.clear(); // 清空 group 内容
                group = null;
                if (callback) callback();
            }
        };

        disposeBatch();
    }
};