javascript / intermediate
Snippet
Memory-Efficient Metadata with WeakMap
WeakMap stores key-value pairs where keys must be objects. Unlike a regular Map, it does not prevent its keys from being garbage collected if no other references exist, making it perfect for attaching metadata to objects without risking memory leaks.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const userState = new WeakMap();function initializeUser(user) {userState.set(user, { startTime: Date.now(), attempts: 0 });}let currentUser = { id: 42, name: 'Niklas' };initializeUser(currentUser);// Metadata is automatically cleared when currentUser is garbage collectedcurrentUser = null;
nodejs
Breakdown
1
const userState = new WeakMap();
Creates a map that holds weak references to its keys.
2
userState.set(user, { ... });
Associates metadata with the specific object instance.
3
currentUser = null;
Removes the last reference; the entry in WeakMap will be automatically deleted by GC.