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.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay