EN/CH Mode
BRUCE_FE JS Interview Notes - Implementing Memoize Function
Learn how to implement JavaScript memoization functions, improve function execution efficiency, avoid repeated calculations, and master caching strategies and their applications in frontend development.
EN/CH Mode
Lazy to read articles? Then watch videos!
What is Memoize
Memoization is an optimization technique that speeds up program execution by storing the results of expensive function calls and returning cached results when the same inputs occur again. It's mainly applicable to pure functions in functional programming (same input always produces same output).
Core Concepts of Memoization
- 1.
Cache Results
: Store function call results - 2.
Cache Hit
: Return previously calculated results when same parameters are called again - 3.
Pure Functions
: Functions with no side effects and output determined only by input, suitable for memoization - 4.
Performance Optimization
: Significantly reduce time cost of repeated calculations
Implementing Basic Memoize Function
Below is a basic memoize function implementation that can memorize results of any pure function:
function memoize(fn) {
// Create cache object
const cache = {};
// Return a new function
return function(...args) {
// Convert parameters to string as key
const key = JSON.stringify(args);
// Check if result exists in cache
if (key in cache) {
console.log('Returning result from cache');
return cache[key];
}
// If no cache, call original function to calculate result
const result = fn.apply(this, args);
// Store result in cache
cache[key] = result;
return result;
};
}
Usage Example
// Calculate Fibonacci sequence
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Non-memoized function call (poor performance)
console.time('Non-memoized');
console.log(fibonacci(35)); // This will take a long time
console.timeEnd('Non-memoized');
// Memoized version
const memoizedFibonacci = memoize(function(n) {
if (n <= 1) return n;
return memoizedFibonacci(n - 1) + memoizedFibonacci(n - 2);
});
// Memoized function call (significantly improved performance)
console.time('Memoized');
console.log(memoizedFibonacci(35)); // Returns result quickly
console.timeEnd('Memoized');