Search code examples
javascriptdictionarycollectionsgarbage-collectiones6-map

Does clearing a map aid with garbage collection?


I recently noticed that my colleague tends to clear any maps before they get dereferenced, such as at the end of a function.

His argument for this is that it's good practice for garbage collection, and I was curious if this is true or a case of over-optimization?

Example:

function useMap() {
  const map = new Map();
  // do stuff
  map.clear();
}

Solution

  • Assuming the javascript runtime in question uses a tracing garbage collector (most do) it will only visit and do work on objects reachable from GC roots. Since the map itself is not reachable it does not matter whether there are still references within the map, they will never be visited.

    Note that similar questions have been asked for C# and Java among others. The underlying mechanisms are very much the same, so such questions could be asked in a language-independent manner based on garbage collector theory.