1

I'm extending this question: Would a "circular" reference be treated as "reachability" for a WeakMap?

If I have 2 WeakMaps that have entries whose values cross references the keys, would this prevent garbage collection or not?

Example:

    let obj1 = {}, obj2 = {}
    obj1.ref = obj2
    obj2.ref = obj1

    const map1 = new WeakMap([[obj2, obj2]])
    const map2 = new WeakMap([[obj1, obj1]])

    obj1 = obj2 = null

    // obj1, obj2 garbage collected?

Answer in this question assume but doesn't confirm: Can a bi-directional WeakMap lead to a memory leak?

  • I think this should work (objects should be garbage collected) as they are not strongly reachable from any GC root. – ewramner Nov 20 '22 at 15:47
  • No, this does not prevent garbage collection. Neither `obj1` nor `obj2` are kept alive by anything. – Bergi Nov 20 '22 at 17:18

0 Answers0