简体   繁体   中英

Javascript Garbage Collector not clearing objects

I've spent a few days searching through SO, googling, and reading articles, and I cannot for the life of me figure out how to avoid memory leaking. I wrote a quick demo to see what was going on here: 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>

The intended result is that once you open the page, the base amount of Memory is stored. You can run go() , and see the memory increase. Once you click something, the object should remove itself from the global scope. On chrome I run the garbage collector, but afterward there is no change in the amount of memory used. It should return to the original memory should it not?

Some of the things I've done: - Made sure all the events are removed - set object to null - cleared out the canvas

I've been trying to understand this for days, any help would be appreciated.

Credit to @JonasW.

He mentioned that garbage collectors only will collect data if there is data to collect, and they won't get kilobytes of data. I modified my codepen to created 25MB of useless data and it ended up working. The codepen saved ended up created kilobytes of data each type go() was run and then removed. Which was the intention, to get rid of that 25MB every time it ran.

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM