当我们在threeJS 中创建了大量资源时候,且不断更换的时候如果我们没用及时将不需要的用物体清理掉就会造成程序的内存泄露,那我么应该怎样及时销毁提升网页性能呢?
例如我们不断在renderer时候创建物体
function render(){
// 创建一个物
const sphereGeometry = new THREE.SphereGeometry(2,Math.random() * 32,Math.random() * 32);
const sphereMaterial = new THREE.MeshBasicMaterial({
color: Math.random * 0xffffff
})
const sphere = new THREE.Mesh(sphereGeometry,sphereMaterial);
scene.add(sphere);
requestAnimationFrame(render)
}
运行的时候我们可以打开控制台可以发现 内存跟cpu在一直上升
这时我们要怎么做才能控制内存跟cpu因为不断创建资源导致内存,cpu资源上升呢
function render(){
...
// 点点点代码未第一段代码块内代码
1. 首先清除后续不再场景中使用的物体
scene.remove(sphere);
// 在执行完,调用销毁函数既可
sphereGeometry.dispose();
sphereMaterial.dispose();
...
}