DEV Community

Jenish Dabhi
Jenish Dabhi

Posted on

Optimizing JavaScript Functions with Memoization

Memoization is a powerful optimization technique used to speed up function calls by caching previously computed results. This is particularly useful for functions that perform expensive calculations or recursive operations. In this blog post, we’ll explore the concept of memoization in JavaScript with a practical example.

What is Memoization?
A memorized function is a technique where the results of function calls are cached so that repeated calls with the same arguments return the cached result instead of recomputing the output.

Example: Fibonacci Sequence

function memoizedFibonacci() {
    const cache = {};

    return function fib(n) {
        if (n in cache) return cache[n];
        if (n <= 1) return n;

        cache[n] = fib(n - 1) + fib(n - 2);
        return cache[n];
    };
}

const fibonacci = memoizedFibonacci();

console.log(fibonacci(10)); // Output: 55
console.log(fibonacci(50)); // Output: 12586269025
Enter fullscreen mode Exit fullscreen mode

How It Works

1. Cache Initialization: We create a cache object to store previously computed Fibonacci numbers.
**2. Closure: **The fib function is returned from memoizedFibonacci, allowing it to access the cache variable.

3.Check Cache
Before performing the calculation, we check if the result is already in the cache. If it is, we return the cached value.
4. Store Result: If the result is not cached, we compute it, store it in the cache, and then return it.

Benefits of Memoization

  • Performance Improvement: Reduces the number of function calls, leading to faster execution times.

  • Simplicity: Easy to implement and understand, especially for recursive functions.

Top comments (0)