javascriptgarbage-collectionobject-reference

JavaScript class field references and garbage collection


I implemented a class that can be used to instantiate objects passed to a visitor function that detects duplicated keys in a JSON document. The problem I am trying to solve is detecting duplicate keys that are in a JSON document. More specifically, I want to detect duplicates at the same nesting level, which I will refer to as context from now on.

The class I implemented has 2 fields:

My question is the following:

Do I need to clear the Set from the references they might holds to the keys when I pop them out of the stack? In other words, is the discarded?.clear() call necessary as the set holds string references to the visited keys?

I understand that the set reference itself will be lost but I am wondering about the references that the set holds (to the visited keys in the json document)

class DetectDuplicates {
  stack;
  visited;

  constructor() {
    this.stack = [];
    this.visited = new Set();
  }

  onObjectBegin() {
    this.stack.push(new Set());
    this.visitedKeys = this.stack[this.stack.length - 1];
  }

  onObjectEnd() {
    const discarded = this.stack.pop();
    // Is that necessary?
    discarded?.clear();
    this.visitedKeys = this.stack[this.stack.length - 1];
  }

}


Solution

  • Do I need to clear the Set from the references they might holds to the keys when I pop them out of the stack?

    No. If the Set instance is not referenced from anywhere else, it will get garbage-collected, and will take with it all the references stored within it.