I have a parent / child relationship that looks like this.
parent.children = [child];
child.parent = parent;
Will this cause memory leak, when all other references to parent
and child
are removed? Only references that are remaining will be by each other.
If it will cause memory leak due to cyclic reference, will WeakMap
save me?
Using WeakMap
,
var parentMap = new WeakMap();
parent.children = [child];
parentMap.set(child, parent);
I guess that it won't since, parentMap
has a reference to parent
, and parent
has a reference to child
. There still is a cyclic reference.
No. If you remove all other references to parent
and child
, they are going to be garbage collected.
All modern browsers use a mark-and-sweep algorithm for the garbage collection with which cycles are not a problem.
You don't need to use a WeakMap
(it won't help you for this anyway).
However, obviously, if a reference to either parent
or child
still exists somewhere, none of them will go.