SoFunction
Updated on 2025-04-07

JavaScript WeakMap Specific Use

Preface

I was exposed to WeakMap when dealing with a deep copy method of a complex object, which acts as a cache structure to solve the circular reference problem inside the object. To remodel this method, I decided to study WeakMap.

1. Why choose WeakMap

WeakMap and Map can use objects as keys, and Map can also use basic data types as keys. In special cases (both use objects as keys), there seems to be no difference between the two.

1. Map

Map will prevent JavaScript's memory recovery mechanism from recycling elements that take an object that has been recycled as a key.
Related to the way elements are stored in the Map:

A map API could be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods.
`map` can be implemented in JavaScript by making two arrays share in 4 methods. When setting elements into `Map`, the key and value `push` are respectively pushed into these two arrays.
Setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously.
When accessing the `Map` value, you need to traverse and find the matching value from two arrays.

var sayings = new Map();
('dog', 'woof');
('cat', 'meow');
('elephant', 'toot');
; // 3
('fox'); // undefined
('bird'); // false
('dog');
('dog'); // false

for (var [key, value] of sayings) {
  (key + ' goes ' + value);
}
// "cat goes meow"
// "elephant goes toot"

();
; // 0

First of all, the Map is implemented internally based on arrays. It takes traversal to get value assignments, and the time complexity is coming:

The first one is an O(n) set and search (n being the number of keys in the map)
First, the time complexity of setting and search is O(n), and n is the number of keys in the Map.
since both operations must iterate through the list of keys to find a matching value.
Because both operations have to iterate through each key to find a matching value.

Secondly, the array will always retain references to elements, which has nothing to do with whether the element is a reference type. As long as the array is not destroyed, the references to elements will not be destroyed:

let ele1 = 'ele1';
let ele2 = { key: 'value' };

let arr = [ ele1, ele2 ];

ele1 = null; // Set to null to detach from the current execution environment so that the recycling mechanism can recycle it = null;

(arr);
// [ 'ele1', { key: 'null' } ]

As mentioned earlier, the Map can be implemented through two arrays, which means that before the Map needs to be destroyed, the keys and values ​​in the Map cannot be recycled by the JavaScript garbage collection mechanism, and the Map may become bloated and large, resulting in insufficient memory (memory leak).

Holding a map referenced by the original object actually means that the object cannot be garbage collected, which can lead to unexpected memory problems.
If you want the objects stored in the map to have the same life cycle as the original object, consider using WeakMap.

2. WeakMap

WeakMap is a collection of key-value pairs, but its key is weakly maintained, that is, when the object referred to by the key is not referenced elsewhere, it will be recycled by the garbage collection mechanism.
Its key must be an object, and the value can be of any data type.

Also because of the garbage collection implemented by this weak reference, the existence of elements in WeakMap becomes unpredictable (the garbage collection mechanism may not be recycled here at present, but it should be recycled here.), in order to prevent accidents during execution, WeakMap does not provide an enumeration method.

Because of such weak references, the keys of WeakMap are not enumerable (no method can give all keys).
If the key is enumerable, its list will be affected by the garbage collection mechanism, resulting in uncertain results.

However, the interface provided by WeakMap is the same as that of Map, and elements can be accessed stably through the interface.

let ele1 = { key: "value" };

let weak = new WeakMap();
(ele1, "ele1");

ele1 = null;

(weak); // WeakMap { <items unknown> } The result is the same here without assigning null((ele1)); // undefined destroy No assignmentnullHere is'ele1'

In short, compared to Map, it is cleaner and more memory-saving.
But if you have an enumeration requirement, or you need to keep the key and not recycle it, then use Map.

2. WeakMap prototype method

Indicate what kind of operation is needed, and specify the key of the key-value pair to be operated, and just pass the variable directly.

method describe
.delete(key) deleteWeakMapThe key matchesvalue.
.get(key) returnWeakMapMiddle andkeyThe associated value, ifkeyIf it does not exist, it will returnundefined.
.has(key) Returns a boolean value, assertWeakMapThe object iskeyWhether it exists.
.set(key, value) TowardsWeakMapSet a new set of key-value pairs in the setWeakMapObject.

Summarize

This is the end of this article about the specific use of JavaScript WeakMap. For more related JavaScript WeakMap content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!