This Website Uses Cookies

Read our privacy policy and terms of use for more information.

  • The Frontend Feed
  • Posts
  • Memoization in JavaScript: Optimize Your Functions for Better Performance

Memoization in JavaScript: Optimize Your Functions for Better Performance

Memoization is a powerful technique in JavaScript that allows you to optimize the performance of your functions by caching the results of expensive operations. This can be especially useful in scenarios where the same inputs are used repeatedly, allowing you to avoid unnecessary calculations.

What is Memoization?

Memoization is a form of caching where the results of function calls are stored so that the next time the same inputs are used, the cached result is returned instead of recomputing the result. This can significantly reduce the time complexity of your functions, especially in cases of expensive computations.

Basic Memoization Example

Let’s start with a basic implementation of a memoized function in JavaScript.

// Memoization
function memoize(func) { 
  let cache = {};  
   
  return (...args) => {  
    const key = JSON.stringify(args); 
     
    if (key in cache) { 
      return cache[key]; 
    } 
     
    cache[key] = func.call(this, args); 
    return cache[key]; 
  } 
}

// slow function
function slowFunction(num) {
  // simulate a time-consuming operation
  return num * num;
}

const memoizedSlowFunction = memoize(slowFunction);

console.log(memoizedSlowFunction(5)); // Computed: 25
console.log(memoizedSlowFunction(5)); // Cached: 25

Pros: Simple to implement, provides immediate performance benefits for functions with repetitive inputs.

Cons: Cache can grow indefinitely if not managed, which might lead to memory issues in long-running applications.

Time-Based Cache Expiry

While basic memoization works well, there are cases where you might want to invalidate the cache after a certain period. This is useful when dealing with data that might change over time, such as API responses.

Here’s a variant of the memoization function with time-based expiry:

// memoization with time-based expiry
function memoizeWithExpiry(func, expiry = 60000) { // Default expiry is 1 minute
  let cache = {};  

  return (...args) => {  
    const key = JSON.stringify(args); 
    const now = Date.now();

    if (key in cache && (now - cache[key].timestamp) < expiry) { 
      return cache[key].value; 
    } 

    const result = func.call(this, args); 
    cache[key] = { value: result, timestamp: now };
    return result; 
  } 
}

// Usage example
const memoizedWithExpiry = memoizeWithExpiry(slowFunction, 30000); // Cache expires after 30 seconds

console.log(memoizedWithExpiry(5)); // Computed: 25
setTimeout(() => console.log(memoizedWithExpiry(5)), 10000); // Cached: 25 (within 30 seconds)
setTimeout(() => console.log(memoizedWithExpiry(5)), 31000); // Computed again: 25 (after expiry)

Pros: Adds control over cache size and relevance by allowing cache entries to expire.

Cons: Slightly more complex than basic memoization, introduces additional overhead for managing timestamps.

When to Use Memoization?

• Expensive Calculations: Functions that perform heavy computations or operations that don’t change often.

• Repetitive Inputs: Scenarios where the same input values are used multiple times within a short period.

• API Calls: For caching API responses that may not change frequently, reducing the number of network requests.

Common Pitfalls to Avoid:

• Memory Consumption: Uncontrolled caching can lead to memory bloat if not managed carefully. Time-based expiry or cache size limits can help mitigate this.

• Over-Optimization: Not every function needs memoization. Use it where performance gains are clear and necessary.

Further Reading:

Memoization is a valuable tool for optimizing JavaScript functions, particularly in performance-critical applications. By understanding and implementing memoization, including variants like time-based expiry, you can make your code more efficient and responsive.

🚀 If you enjoyed this post, why not show your love for coding with our Javascript Developer Themed Tees from Usha Creations? Discover the perfect shirt for your next hackathon!

Reply

or to participate.