Does ES6 const affect garbage collection?

前端 未结 4 1457
鱼传尺愫
鱼传尺愫 2021-02-02 11:45

In Kyle Simpson\'s new title, You don\'t know JS: ES6 and beyond, I find the following snippet:

WARNING Assigning an object or array as a constan

4条回答
  •  既然无缘
    2021-02-02 12:36

    No, there are no performance implications. This note refers to the practise of helping the garbage collector (which is rarely enough needed) by "unsetting" the variable:

    {
        let x = makeHeavyObject();
        window.onclick = function() {
            // this *might* close over `x` even when it doesn't need it
        };
        x = null; // so we better clear it
    }
    

    This is obviously not possibly to do if you had declared x as a const.

    The lifetime of the variable (when it goes out of scope) is not affected by this. But if the garbage collector screws up, a constant will always hold the value it was initialised with, and prevent that from being garbage-collected as well, while a normal variable might no more hold it.

提交回复
热议问题