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
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
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
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
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 DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.