【发布时间】:2018-03-06 20:55:38
【问题描述】:
我花了几天时间搜索 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 上我运行垃圾收集器,但之后使用的内存量没有变化。应该不会回到原来的记忆吧?
我做过的一些事情: - 确保所有事件都被删除 - 将对象设置为空 - 清除画布
这几天我一直在努力理解这一点,如果有任何帮助,我们将不胜感激。
【问题讨论】:
-
确保你的记忆被填满,否则大多数收藏家实际上不会收集太多
-
@Jonas W,他们不应该在我的 SelectMap 对象中收集变量吗?
-
改写:@Jonas_W 是什么意思?
-
收藏家为什么要收藏?您的应用程序可能不需要内存,那么为什么要花时间(= 性能)来获得不需要的内存
-
在我编写的实际软件中,我遇到了内核恐慌(应该归咎于 safari,但 Firefox 变得无响应),但我明白你在说什么。如何测试 GC?
标签: javascript object memory