DEV Community

Jenish Dabhi
Jenish Dabhi

Posted on

1 1 1 1

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay