WeakMap vs Map: Utilise garbage collection in JavaScript
We all know JavaScript is one of the programming languages that does garbage collection on its own. It is done usually using mark and sweep algorithm.
What does mark and sweep algorithm mean?
It starts from the root(global or window), and tries to reach the references one-by-one-level-down each to get all the referenced variables in the current execution context. The node or a sub-tree which is independent and not referenced is garbage collected.
What’s different in WeakMaps then?
While AI empowers designers, it also raises challenges:
The story of Maps and WeakMaps start to begin when we want to associate objects with some certain metadata. WeakMaps differ from Maps in having weak references, rather than strong references to its keys, i.e., objects. Once the object which is key of WeakMap is found abandoned by garbage collector, it removes it. While in Map, the object is kept in memory until and unless it references it.
Example:
let map = new Map();
let obj = {};
map.set(obj, "some value"); // map now holds a strong reference
to obj as the key
console.log(map.get(obj)); // "some value"
// we remove the strong reference
obj = null;
The variable obj
no longer references the object, but the object is still referenced as a key in map
. That's not the case in WeakMap.
Conclusion
Associations are done, while keeping in mind efficient memory management. Limitation is we can’t iterate and lose control over the data-structure, but it is a good choice for data association for private objects, temporary object caches.