Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Memoizing a Complex Calculation:
4.2.
JavaScript
4.3.
Custom Resolver Function:
4.4.
JavaScript
4.5.
Memoizing Recursive Functions:
4.6.
JavaScript
4.7.
Improving Rendering Performance:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
How does memoization affect memory usage?
5.2.
Can the cache of a memoized function be cleared?
5.3.
Is _.memoize() suitable for all kinds of functions?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.memoize() Method

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Efficiency in function execution is vital, especially for resource-intensive or frequently called functions. Lodash enhances JavaScript's capabilities in this regard with the _.memoize() method. This function creates a memoized version of a function, caching the computed result of the function for given arguments. 

Lodash _.memoize() Method

This is particularly useful for optimizing performance in scenarios involving expensive function calls.

Why This Function is Used

The _.memoize() function is used to boost performance by caching the results of function calls. When a function is called with a new set of arguments, it calculates the result and stores it. Subsequent calls with the same arguments return the cached result, avoiding the need for re-computation. This is especially beneficial for functions with costly operations or those called repeatedly with the same arguments, such as complex calculations, data retrieval operations, or rendering tasks.

Syntax, Parameter and Return Value

Syntax: 

_.memoize(func, [resolver])

Parameters:

  • func (Function): The function to have its output memoized.
     
  • [resolver] (Function): The function to resolve the cache key for storing results.

Return Value: 

(Function) - Returns the new memoized function.

Examples 

Memoizing a Complex Calculation:

  • JavaScript

JavaScript

var _ = require('lodash');

function complexCalculation(a, b) {

 // Simulate expensive operation

 console.log('Calculating...');

 return a * b;

}

var memoizedCalc = _.memoize(complexCalculation);

console.log(memoizedCalc(2, 3));

console.log(memoizedCalc(2, 3));
You can also try this code with Online Javascript Compiler
Run Code

Output: 

Calculating... 6


6 (cached result, no 'Calculating...' message)

Demonstrates memoizing a function to optimize repeated calls with the same arguments.

Custom Resolver Function:

  • JavaScript

JavaScript

function fetchData(id) {

 console.log('Fetching data for ID:', id);

 // Fetch and return data

}

var memoizedFetch = _.memoize(fetchData, id => id.toLowerCase());

memoizedFetch('DataID'); // Fetching performed

memoizedFetch('dataid'); // Fetching not performed, cached result used
You can also try this code with Online Javascript Compiler
Run Code


Shows using a custom resolver to determine how cache keys are computed.

Memoizing Recursive Functions:

  • JavaScript

JavaScript

var memoizedFactorial = _.memoize(function factorial(n) {

 console.log('Calculating factorial for:', n);

 return n <= 1 ? 1 : n * factorial(n - 1);

});

console.log(memoizedFactorial(5)); // Calculations performed for 5, 4, 3, 2, 1

console.log(memoizedFactorial(5)); // Cached result used
You can also try this code with Online Javascript Compiler
Run Code


An example of memoizing a recursive function to enhance performance.

Improving Rendering Performance:

  • JavaScript

JavaScript

function renderUser(user) {

 console.log('Rendering user:', user.name);

 // Render user details

}

var memoizedRender = _.memoize(renderUser, user => user.id);

var user = { id: 'u1', name: 'Alice' };

memoizedRender(user); // Rendering performed

memoizedRender(user); // Cached result used, no rendering
You can also try this code with Online Javascript Compiler
Run Code


Demonstrates memoizing a rendering function to avoid unnecessary re-rendering.

Frequently Asked Questions 

How does memoization affect memory usage?

While memoization improves performance by caching results, it can increase memory usage, especially if used on functions with a vast range of arguments or large result sets.

Can the cache of a memoized function be cleared?

Yes, the cache of a memoized function (accessible via memoizedFunction.cache) can be cleared, allowing for manual control over memory usage.

Is _.memoize() suitable for all kinds of functions?

_.memoize() is most suitable for pure functions (functions where the output depends only on the input and has no side effects). Using it on impure functions may lead to unexpected results.

Conclusion

Lodash's _.memoize() method is an effective tool for optimizing performance, particularly when a function is repeatedly called with the same arguments. It reduces computational overhead by caching results, making it an essential technique in resource-intensive operations.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass