JavaScript WeakMap keep referencing gc'ed objects

前端 未结 1 1761
时光取名叫无心
时光取名叫无心 2021-01-18 11:19

I am experiencing with JavaScript weakmaps, after trying this code in google chrome developer console, running with --js-flags=\"--expose-gc\", I don\'t understand why the w

1条回答
  •  囚心锁ツ
    2021-01-18 11:57

    UPDATE 2/2020

    When I run this code now, it works as expected. I think having the console open was causing objects to be held onto in previous versions of Chrome but not now. Reassigning the value of a variable that holds a reference to an object will cause that object to be garbage collected (assuming nothing else has a reference to it).


    In your example code, you're not releasing your a variable. It's a top level var that never goes out of scope and never gets explicitly de-referenced, so it stays in the WeakMap. WeakMap/WeakSet releases objects once there are no more references to it in your code. In your example, if you console.log(a) after one of your gc() calls, you'd still expect a to be alive, right?

    So here's a working example showing WeakSet in action and how it'll delete an entry once all references to it are gone: https://embed.plnkr.co/cDqi5lFDEbvmjl5S19Wr/

    const wset = new WeakSet();
    
    // top level static var, should show up in `console.log(wset)` after a run
    let arr = [1];
    wset.add(arr);
    
    function test() {
      let obj = {a:1}; //stack var, should get GCed
      wset.add(obj);
    }
    
    test();
    
    //if we wanted to get rid of `arr` in `wset`, we could explicitly de-reference it
    //arr = null;
    
    // when run with devtools console open, `wset` always holds onto `obj`
    // when devtools are closed and then opened after, `wset` has the `arr` entry,
    // but not the `obj` entry, as expected
    console.log(wset);
    

    Note that having Chrome dev tools opened prevents some objects from getting garbage collected, which makes seeing this in action more difficult than expected :)

    0 讨论(0)
提交回复
热议问题