Hone

Lessons · JavaScript · memory for speed

Spend memory to save time

Precompute once into a table, then read from it, instead of recomputing in a loop.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Prefix sums, memoised functions, caches: most real speed-ups are this trade.

How to think about it

Ask: am I recomputing the same thing repeatedly? Compute it once, keep it, read it.

Worked example

const prefix = [0];
prefix[k] = total of first k items.
for (const s of sales) prefix.push(prefix.at(-1) + s);
Built once.
prefix[3] - prefix[1]
Total of items 1 and 2, in one subtraction.

Your turn

Cache results of a slow function.

const cache = new Map();
function fast(n) {
  if (cache.has(n)) return cache.get(n);
  const r = slow(n); cache.(n, r); return r;
}

The trap

A cache that grows forever in a long-lived page. Bound it.

Practise memory for speed on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.