Map vs WeakMap in JavaScript
Introduction
I previously wrote an article about the Map in ES6 JavaScript. This time, let’s discuss WeakMap and how it differs from Map.
You will find that WeakMap
has significantly fewer available methods compared to Map
. This is because they fundamentally handle data differently: Map
uses strong references, while WeakMap
uses weak references.
Characteristics of WeakMap
- Does not prevent keys from being garbage collected: The weak reference mechanism makes WeakMap very useful in scenarios where you need to associate additional data without affecting the lifecycle of the original object, such as: private variables, adding additional information to objects (DOM elements, classes, packages) that can be automatically garbage collected……
- Generally only objects can be used as keys: It serves as a collection of weak pointers. Primitive values (like numbers, strings) are immutable in JavaScript and are not stored by reference, so the concept of weak references cannot be applied to them.
- Does not care about content and state:
WeakMap
cannot know if the JavaScript engine has already garbage collected a certain item, so it cannot guarantee that all items inWeakMap
are valid. It does not support accessing all contents, such as iterating over the contents.
Conclusion
let foo = { name: 'foo' };const map = new Map();map.set(foo, 'Hello');
foo = undefined;
map.forEach((value, key) => { console.log(key, value); // { name: 'foo' } 'Hello'});
// Conclusion: Even if the key is cleared, the map still retains a reference to foo// If you want the map to be cleared along with foo, you can use WeakMap
The design of WeakMap is intended to solve specific issues present in Map
(avoiding memory leaks, allowing the garbage collector to automatically clean up data that is no longer needed), making it suitable to choose the appropriate data structure in the right scenarios.
Further Reading
- WeakMap - mdn
- Map vs WeakMap in javascript - When to use Map vs WeakMap? - Before Semicolon
- WeakMap and WeakSet - JAVASCRIPT.INFO