Search code examples
javascriptgarbage-collectionweak-references

Can a bi-directional WeakMap lead to a memory leak?


From what I know about native JavaScript WeakMaps, they store their keys weakly, but store their values strongly, is that correct?

If so, would using a value as both, a key and a value in a WeakMap prevent the object from being garbage-collected?

const domElement0 = ...;
const domElement1 = ...;

const map = new WeakMap([
    [ domElement0, domElement1 ],
    [ domElement1, domElement0 ]
]);

Assuming that the WeakMap is always available, in that snippet, I would assume that, if domElement0 is unreachable, then domElement1 would not be garbage-collected, and vice versa, but if they both become unreachable and detached from the DOM, can I know that they will both become eligible for GC in most browsers?

If so, can someone provide a reference to why this is possible?


Solution

  • I think they should become garbage.

    The specification of WeakMap Objects has the following note:

    WeakMap and WeakSets are intended to provide mechanisms for dynamically associating state with an object in a manner that does not “leak” memory resources if, in the absence of the WeakMap or WeakSet, the object otherwise became inaccessible and subject to resource reclamation by the implementation's garbage collection mechanisms.

    So if the only references to the objects are through a WeakMap entry, and the keys are not accessible through some chain of references starting outside the WeakMap, the objects become garbage.