DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 46: Memoization

What is Memoization?

Memoization is a technique used to store the results of expensive function calls and return the cached result when the same inputs occur again. It's like having a crystal ball that remembers previous calculations and can instantly provide answers.
๐Ÿช„

Creating the Memoization Decorator

Let's create a TypeScript decorator that can memoize the result of a function. We'll call it @memoize. ๐Ÿ“

function memoize(target: any, key: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  const cache = new Map();

  descriptor.value = function (...args: any[]) {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      return cache.get(key);
    }

    const result = originalMethod.apply(this, args);
    cache.set(key, result);
    return result;
  };

  return descriptor;
}
Enter fullscreen mode Exit fullscreen mode

Applying Decorator

class Calculator {
  @memoize
  static fibonacci(n: number): number {
    if (n <= 1) return n;
    return this.fibonacci(n - 1) + this.fibonacci(n - 2);
  }
}
Enter fullscreen mode Exit fullscreen mode

By adding @memoize to the fibonacci method, we're telling it to cache the results. As a result, subsequent calls with the same argument won't recalculate the Fibonacci number, making our code much faster! ๐Ÿš€

Example

console.log(Calculator.fibonacci(40)); // Calculates Fibonacci(40) and caches it
console.log(Calculator.fibonacci(40)); // Returns the cached result instantly
Enter fullscreen mode Exit fullscreen mode

Benefits of Memoization with Decorators

  • Performance Boost: Memoization can drastically reduce the execution time of functions with expensive calculations.
  • Simplified Code: You don't need to manually implement caching logic in your functions; decorators handle it for you.
  • Readability: Code using decorators is more concise and easier to understand.

Considerations

  • Be cautious when using memoization for functions with a large number of potential input values, as it can lead to excessive memory usage. Always evaluate your use case.

Top comments (0)