I do not understand how this code causes a memory leak.
var theThing = null;
var replaceThing = function () {
var originalThing = theThing;
var unused = function () {
if (originalThing)
console.log("hi");
};
theThing = {
longStr: new Array(1000000).join('*'),
someMethod: function () {
console.log(someMessage);
}
};
};
setInterval(replaceThing, 1000);
If I set it originalThingto zero at the end of the function replaceThing, everything will be fine. But I did not see the reference cycle here, and I do not know why this closure cannot be released.
And does v8 GC use marker sweep? If I put this code in IIFE, a memory leak still exists. But how can the root context reach these variables and functions? I used chrome to check this code. Now I'm confused about how GC works on Closure.
source
share