Search code examples
javascriptmemory-leaksecmascript-6weakmap

Will WeakMap save me from memory leak for parent / child relationship?


I have a parent / child relationship that looks like this.

parent.children = [child];
child.parent = parent;
  1. 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.

  2. 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.


Solution

  • 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.