2

In an implementation I have a tree-like structure with parent and child objects. The parents have a child list and the children a reference to their parents, in order to be able to navigate easily thru the tree. Now I wonder if such a structure would ever be garbage collected, given that we have strong reference cycles here (I'm not aware of weak pointers in TypeScript).

Here's a (dead simple) example for such a structure, though I believe everyone can imagine how that would look like:

class Symbol {
    protected parent: Symbol | undefined;
    protected children: Symbol[];
}

What is the recommended approach for such kind of data structure? Use the (relatively) new WeakMap or WeakSet classes to reference parents (which sounds ugly)?

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181

1 Answers1

1

There are many ways to represent trees, which one is best depends on what you're doing with your tree structure.
If you're content with what you have now and only care about garbage collection, then why not introducing a remove method for your nodes?

class MySymbol {
    protected parent: MySymbol | undefined;
    protected children: MySymbol[];

    remove() {
        this.children = [];
        this.parent && this.parent.childRemoved(this);
    }

    childRemoved(child: MySymbol) {
        this.children.splice(this.children.indexOf(child), 1);
    }
}

(note that I changed Symbol to MySymbol otherwise you get a duplicate name error)

This approach will work only if a child can have just one parent, otherwise this will have to change a bit.


Edit

The only thing that might give you something similar is to use a WeakMap for your children.
Also read the answer here: Creating a regular weak-reference in Javascript using WeakMaps

Community
  • 1
  • 1
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • While I have indeed such a method already, it is not really a solution for this problem, since I would manually have to cleanup up before the garbage collection, which somehow defeats its purpose. What I need is a way to avoid objects referencing each other in a strong way. – Mike Lischke Feb 18 '17 at 19:21