Course contentsShow
← JavaScript
Lesson 2089 of 2,72343. DecoratorsFree lesson

Memoization Decorators

Implement decorators that cache method results to avoid redundant expensive computations.

Memoization Decorators

You'll learn how to build decorators that cache expensive method results to avoid redundant computations.

The Core Idea

Memoization is an optimization technique where you store the results of expensive function calls and return the cached result when the same inputs occur again. A memoization decorator wraps a method to automatically manage this cache, so you never compute the same thing twice.

Think of it like a restaurant kitchen keeping pre-made sauces ready: if someone orders the same dish twice, you use the pre-made sauce instead of making it from scratch each time.

Building a Memoization Decorator

function memoize(fn, context) {
  const cache = new Map();
  
  return function(...args) {
    // Create a cache key from arguments
    const key = JSON.stringify(args);
    
    if (cache.has(key)) {
      console.log('Cache hit!');
      return cache.get(key);
    }
    
    console.log('Computing...');
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

class Calculator {
  @memoize
  fibonacci(n) {
    if (n <= 1) return n;
    return this.fibonacci(n - 1) + this.fibonacci(n - 2);
  }
}

const calc = new Calculator();
calc.fibonacci(40); // Computing... (slow)
calc.fibonacci(40); // Cache hit! (instant)

When This Matters

Memoization decorators shine with:

  • Expensive computations (complex math, recursive algorithms)
  • Pure methods (same inputs always produce same output)
  • Repeated calls with identical arguments

The cache persists for the method's lifetime, so every repeat call avoids re-computation.

Key Takeaway: Memoization decorators automatically cache method results, turning expensive repeated operations into instant lookups—perfect for recursive functions or complex calculations that get called multiple times with the same inputs.