Does ES6 const affect garbage collection?

前端 未结 4 1401
鱼传尺愫
鱼传尺愫 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:32

    That note in my book was referring to cases like this, where you'd like to be able to manually make a value GC'able earlier than the end of life of its parent scope:

    var cool = (function(){
       var someCoolNumbers = [2,4,6,8,....1E7]; // a big array
    
       function printCoolNumber(idx) {
          console.log( someCoolNumbers[idx] );
       }
    
       function allDone() {
          someCoolNumbers = null;
       }
    
       return {
          printCoolNumber: printCoolNumber,
          allDone: allDone
       };
    })();
    
    cool.printCoolNumber( 10 ); // 22
    cool.allDone();
    

    The purpose of the allDone() function in this silly example is to point out that there are times when you can decide you are done with a large data structure (array, object), even though the surrounding scope/behavior may live on (via closure) indefinitely in the app. To allow the GC to pick up that array and reclaim its memory, you unset the reference with someCoolNumbers = null.

    If you had declared const someCoolNumbers = [...]; then you would be unable to do so, so that memory would remain used until the parent scope (via the closure that the methods on cool have) goes away when cool is unset or itself GCd.

    Update

    To make absolutely clear, because there's a lot of confusion/argument in some comment threads here, this is my point:

    const absolutely, positively, undeniably has an effect on GC -- specifically, the ability of a value to be GCd manually at an earlier time. If the value is referenced via a const declaration, you cannot unset that reference, which means you cannot get the value GCd earlier. The value will only be able to be GCd when the scope is torn down.

    If you'd like to be able to manually make a value eligible for GC earlier, while the parent scope is still surviving, you'll have to be able to unset your reference to that value, and you cannot do that if you used a const.

    Some seem to have believed that my claim was const prevents any GC ever. That was never my claim. Only that it prevented earlier manual GC.

提交回复
热议问题