Skip to content
jshacks.dev
Functions

Clear memoization caches to avoid leaks

Clear memoization caches to avoid leaks in JavaScript by bounding the Map, evicting the oldest entries as new ones arrive. Works in any Node.js.

1 min read
Summarize in AI

A memoize wrapper that never forgets will grow with every new input. For a long-running server that is a slow memory leak, so give the cache a limit.

JavaScript
const memoize = (fn, max = 2) => {
  const cache = new Map();
  return (key) => {
    if (cache.has(key)) {
      const value = cache.get(key);
      cache.delete(key);
      cache.set(key, value);
      return value;
    }
    const value = fn(key);
    cache.set(key, value);
    if (cache.size > max) cache.delete(cache.keys().next().value);
    return value;
  };
};

let calls = 0;
const double = memoize((n) => {
  calls++;
  return n * 2;
});

double(1);
double(2);
double(3);
double(1);
console.log(calls);
Text
4

With room for two entries, adding 3 evicted 1, the oldest, so the later call for 1 had to compute again: four calls for four requests, and no hits. A hit moves its key to the end of the Map, so the first key is always the least recently used.

Choose the limit from how much memory a result takes and how often keys repeat. If keys are objects, a WeakMap frees entries by itself, but it cannot be limited or cleared in bulk. Without a bound, at least expose a clear() and call it when the data it depends on changes.

Taggednode 24
Share

More snippets

Functions

Memoize a function with a Map

Memoize a function in JavaScript with a Map keyed by its argument, caching results including undefined. For single-argument pure functions on any Node.js.

1 min read
Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.