- Daishi Kato's Read the Code
- Posts
- When We Should Use WeakMap and WeakSet
When We Should Use WeakMap and WeakSet
Jotai Uses Them a Lot, and You Might Wonder Why
Hi,
I am not sure if I have a good perception of this, but I assume that Map
is fairly widely used, whereas WeakMap
is not as common. WeakMap
is often described as being useful for caching, but I think it is better understood as a specialized version of Map
.
The major differences between Map
and WeakMap
are:
Map
is iterable, whileWeakMap
is not.The keys of a
WeakMap
must be objects or symbols.
Notice that this description does not mention garbage collection. I guess WeakMap
s are designed for garbage collectability, and it’s one of their biggest benefits. However, we could also view this capability as a by-product rather than the primary reason for using them.
When to Use WeakMap
If you are using a Map
, but you do not need to iterate over it and all the keys are objects, you could use a WeakMap
instead. I am not 100% sure of the actual performance differences, but it feels like WeakMap
can be more efficient than Map
in cases where either could be used.
How Jotai Uses WeakMap
In the Jotai codebase, we use WeakMap
wherever possible. In particular, for atoms, we use WeakMap
to ensure that atom values are garbage-collected when their references are no longer used.
We even have unit tests to verify this behavior. If you are interested, feel free to check them out: Jotai Memory Leak Tests
A Note on WeakSet
The same applies to WeakSet
. If we use a Set
only for objects and do not need to iterate over them, we can use WeakSet
instead.
Happy coding.
Reply