Why is this js function causing a memory leak?

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.

+4
source share
2 answers

, originalThing null, theThing , originalThing , theThing , originalThing

0

Source: https://habr.com/ru/post/1670993/


All Articles