Sitemap
Vinay Somawat

Vinay Somawat

Senior Frontend Engineer building scalable UI with Angular, React, and TypeScript.

Optimizing Function Performance in JavaScript with Memoization

2 min readSep 25, 2024

--

In JavaScript, functions often perform repetitive tasks with the same input values. These repeated computations can slow down an application’s performance, especially when the function is resource-intensive. One effective solution to this problem is memoization.

Memoization is a technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. Let’s walk through a simple implementation of memoization in JavaScript.

Basic Memoization in JavaScript

We’ll implement a memo function that takes a callback function (cb) as an argument and returns a new function that caches its results based on the inputs. For demonstration, we will use a basic add function that adds two numbers.

Get Vinay Somawat’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s the implementation:

let cache = {};

function memo(cb) {
return function(...args) {
// Check if the result for these arguments is already cached
if(cache[JSON.stringify(args)]) {
console.log('cache result');
return cache[JSON.stringify(args)];
} else {
console.log('executed result');
const res = cb(...args);
// Store the result in the cache
cache[JSON.stringify(args)] = res;
return res;
}
}
}

function add(a, b) {
return a + b;
}

const memoize = memo(add);

// Testing the memoized function
memoize(1, 2); // Outputs: executed result
memoize(2, 3); // Outputs: executed result
memoize(1, 2); // Outputs: cache result
memoize(4, 5); // Outputs: executed result
memoize(2, 3); // Outputs: cache result

How It Works

  1. Cache Creation: We use a simple cache object to store results. The keys of this object are the stringified arguments passed to the memoized function, and the values are the results returned from the original function.
  2. Memo Function:
  • The memo function takes another function (cb) as an argument.
  • Inside, it returns a new function that accepts any number of arguments (...args).
  • When this new function is called, it checks if the result for the given arguments already exists in the cache (using JSON.stringify(args) as the key).
  • If the result is cached, it returns the cached value and logs 'cache result'.
  • If the result is not cached, it calls the original function cb, stores the result in the cache, and logs 'executed result'.

3. Memoizing the add Function: We pass the add function to memo, creating a memoized version of add. The memoized function will now return cached results for previously computed inputs.

Key Takeaways

  • Performance Boost: Memoization is especially useful when dealing with expensive operations like recursive algorithms, complex calculations, or API calls. It prevents recalculating the same result and thus improves the performance.
  • Trade-off: While memoization improves time complexity, it uses additional space to store results, so it’s important to ensure that the memory usage doesn’t grow too large, especially for functions with many possible argument combinations.

Conclusion

Memoization is a powerful optimization technique that can significantly boost the performance of your JavaScript applications. It’s particularly useful in scenarios where functions are called repeatedly with the same inputs, as it avoids redundant calculations by returning cached results.

This example shows how easy it is to implement memoization in JavaScript. As your applications grow, using this technique where appropriate can lead to better performance and responsiveness.

--

--

Vinay Somawat
Vinay Somawat

Written by Vinay Somawat

Senior Frontend Engineer building scalable UI with Angular, React, and TypeScript.