我花了几天时间搜索 SO、谷歌搜索和阅读文章,但我终其一生都想不出如何避免内存泄漏。我写了一个快速演示来查看这里发生了什么:https://codepen.io/dotjersh/pen/WMVwWx .
var SelectMap = function(canvas,onComplete){
var size = [3,3];
var s = 39;//sidelength
var p = 1; //padding
var color = ['#3D5AFE','#F57F17']
var ctx = canvas.getContext("2d");
var cursor = null;
canvas.width = size[0] * (s + p);
canvas.height = size[1] * (s + p);
canvas.addEventListener('mousemove',hover);
canvas.addEventListener('click',click);
render();
function click(e){
onComplete(Math.floor(cursor.x/(s + p)),Math.floor(cursor.y/(s + p)));
destroy();
}
function hover(e){
cursor = {x:Math.abs(e.clientX - canvas.offsetLeft),y:Math.abs(e.clientY - canvas.offsetTop)}
render();
}
function render(){
ctx.clearRect(0,0,canvas.width,canvas.height)
for(var x = 0; x < size[0]; x++){
for(var y = 0; y < size[1]; y++){
ctx.fillStyle = color[0];
if(cursor){
var xPoint = ((x*s) + (x*p));
var yPoint = ((y*s) + (y*p));
if(Math.floor(cursor.x/(s + p)) == x && Math.floor(cursor.y/(s + p)) == y){
ctx.fillStyle = color[1];
}
}
ctx.fillRect((x*s) + (x*p),(y*s) + (y*p),s,s);
}
}
}
function destroy(){
canvas.removeEventListener('mousemove',hover);
canvas.removeEventListener('click',click);
ctx.clearRect(0,0,canvas.width,canvas.height);
}
return{
destroy: destroy,
}
}
function go(){
var bob = new SelectMap(document.getElementById('canvas'),function(x,y){
alert(x + "," + y);
bob = null;
});
}
<canvas id="canvas"></canvas>
预期的结果是,一旦您打开页面,就会存储基本内存量。您可以运行 go()
,然后看到内存增加。单击某物后,该对象应将其自身从全局范围中移除。在 chrome 上,我运行垃圾收集器,但之后使用的内存量没有变化。应该不会回到原来的内存吧?
我做过的一些事情: - 确保删除所有事件 - 将对象设置为空 - 清除 Canvas
几天来我一直在努力理解这一点,我们将不胜感激。
最佳答案
归功于@JonasW。
他提到垃圾收集器只有在有数据要收集的情况下才会收集数据,他们不会得到千字节的数据。我修改了我的 codepen 以创建 25MB 的无用数据,它最终可以正常工作。保存的代码笔最终创建了千字节的数据,每种类型的 go() 被运行然后被删除。其目的是在每次运行时摆脱那 25MB。
谢谢!
关于Javascript 垃圾收集器不清除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49139795/