Memory leaks and closures in JavaScript - when and why?

前端 未结 3 369
感情败类
感情败类 2020-12-12 10:35

You quite often read on the web that using closures is a massive source of memory leaks in JavaScript. Most of the times these articles refer to mixing script code and DOM e

3条回答
  •  感情败类
    2020-12-12 11:15

    You can find a good example and explanation in this blog post by David Glasser.

    Well, here it is (I added a few comments):

    var theThing = null;
    var cnt = 0; // helps us to differentiate the leaked objects in the debugger
    var replaceThing = function () {
        var originalThing = theThing;
        var unused = function () {
            if (originalThing) // originalThing is used in the closure and hence ends up in the lexical environment shared by all closures in that scope
                console.log("hi");
        };
        // originalThing = null; // <- nulling originalThing here tells V8 gc to collect it 
        theThing = {
            longStr: (++cnt) + '_' + (new Array(1000000).join('*')),
            someMethod: function () { // if not nulled, original thing is now attached to someMethod ->  -> Closure
                console.log(someMessage);
            }
        };
    };
    setInterval(replaceThing, 1000);
    

    Please try it out with and without nulling originalThing in Chrome Dev Tools (timeline tab, memory view, click record). Note that the example above applies to browser and Node.js environments.

    Credit also and especially to Vyacheslav Egorov.

提交回复
热议问题