Search code examples
javascriptdictionaryecmascript-6weakmap

When would you use a Map over a WeakMap when you have objects as keys?


The few times that I've used objects as keys in a map I did it to store metadata about that specific object. I've always used a WeakMap for this because of the benefit of the entry in the map being garbage collected automatically when the object it was using as a key gets garbage collected.

Storing metadata is the only use case I can think of for objects as keys in maps, but I'm curious if there are other use cases for objects as keys and if in those cases, you'd use a regular Map over a WeakMap.


Solution

  • Consider an implementation for modeling graphs. Lets assume nodes of the graph can be user defined objects. The graph implementation needs to store those nodes but also associate them with other data (such as edges (think of an adjacency "dictionary")). We would need a Map since we have to be able to iterate over all nodes as well (that's e.g. what networkx.github.io does (in Python) and my JS port of it)

    And even if we didn't need to iterate over the nodes, we probably wouldn't want them to be garbage collected if there are no other references to them, since that would silently destroy the graph.

    - Felix Kling