What is the main advantage of using WeakMap in this caching scenario?
const cache = new WeakMap();
class ExpensiveOperation {
compute(obj) {
let result = cache.get(obj);
if (result === undefined) {
result = /* expensive computation */;
cache.set(obj, result);
}
return result;
}
}
WeakMap provides optimal caching behavior: 1) It caches computation results without preventing garbage collection of unused objects, 2) Cache entries are automatically removed when their key objects are no longer referenced elsewhere, 3) This prevents memory leaks that would occur with a regular Map, 4) The cache self-manages its memory usage based on object lifecycle, 5) This is particularly valuable for expensive computations on objects that may become unused, 6) No explicit cache invalidation or cleanup code is needed, 7) The pattern is memory-efficient for long-running applications, 8) This demonstrates a practical use case where WeakMap's characteristics provide clear benefits.