Optimize your Javascript Code with this method

Rizwanhoda
3 min readMar 28, 2024

--

Photo by Joshua Aragon on Unsplash

Introduction:

In JavaScript programming, making your code run faster is a big win. Memoization is a clever trick that helps your functions work quicker by remembering their previous results. Let’s explore what memoization is, how it works, and how you can use it to make your JavaScript code lightning fast.

What is Memoization?

Memoization is like having a smart assistant for your functions. It remembers the answers they’ve given before so it doesn’t have to do the work again if it gets asked the same question

How Does Memoization Work?

Imagine you have a function that takes some inputs and gives you an output. Memoization stores the answers the function gives for different inputs. So, the next time you ask the function the same question, it already knows the answer and gives it to you instantly, without doing all the work again.

To understand how memoization actually work behind the scene first you have to understand the concept of the closures

let’s break down the process step by step

Closure Creation: When you create a memoized function, you typically define a higher-order function that returns a new function. This higher-order function serves as the closure.

function memoize(func) {
const cache = {}; // Cache for storing results

// Closure: Returned function has access to 'cache'
return function(...args) {
const key = JSON.stringify(args); // Serialize arguments
if (!cache[key]) {
cache[key] = func.apply(this, args); // Compute and store result
}
return cache[key]; // Return cached result
};
}
  1. Access to Outer Scope: The returned function, known as the memoized function, retains access to the variables and parameters of the outer function (i.e., the closure). In this case, it has access to the cache object.
  2. Persistent State: The closure ensures that the cache object persists across multiple invocations of the memoized function. This means that the cache is not reset every time the memoized function is called.
  3. Private Scope: Since the cache object is defined within the closure, it remains private to the memoized function. Other parts of the program cannot directly access or modify the cache, ensuring data integrity.
  4. Efficient Caching: When the memoized function is called with a set of arguments, it first checks if the result for those arguments is already present in the cache. If the result is found, the memoized function returns the cached result without re-computing it.
  5. Storing Results: If the result is not found in the cache, the memoized function computes the result using the original function (func) and stores the result in the cache for future use.
  6. Result Return: Finally, the memoized function returns the computed result to the caller.

Implementing Memoization in JavaScript

To use memoization, you create a special version of your function that remembers its previous answers. Here’s a simple way to do it:

function memoize(func) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (!cache[key]) {
cache[key] = func.apply(this, args);
}
return cache[key];
};
}

// Example usage
const expensiveFunction = memoize((n) => {
console.log('Calculating...');
return n * 2;
});

console.log(expensiveFunction(5)); // Output: Calculating... 10
console.log(expensiveFunction(5)); // Output: 10 (cached result)

In this example, the memoize function wraps around your original function, creating a cache to remember its results. So, if you call the function with the same inputs again, it quickly gives you the answer it remembered, without doing the calculation again.

In summary, memoization closures work by encapsulating the caching logic within a closure. This allows the memoized function to efficiently cache and retrieve results across multiple function calls, enhancing performance by avoiding redundant computations. The closure ensures that the cache object remains accessible and private, contributing to the effectiveness of memoization in optimizing function performance.

Benefits of Memoization

  • Faster Performance: Memoization makes your functions run faster by avoiding redundant calculations.
  • Simpler Code: It simplifies your code by storing previous results, making it easier to understand and manage.
  • Efficient Resource Usage: By saving previous answers, memoization helps your code use fewer resources, making it more efficient.

Conclusion

Memoization is a clever trick that can supercharge your JavaScript code by remembering previous function results. By using it, you can make your code faster, simpler, and more efficient. So, next time you want your JavaScript code to run like lightning, remember to give memoization a try!

--

--

Rizwanhoda
Rizwanhoda

Written by Rizwanhoda

Self taught front end developer and uiux designer

No responses yet