Memorization (or "memoization") is an optimization technique that caches the results of heavy or time-consuming functions, so that future calls with the same arguments are faster. Memorization is especially useful in pure functions, where the same set of inputs always produces the same result.
How Does Memorization Work?
When a memorized function is called for the first time with certain arguments, it performs the calculation and stores the result in a cache. On subsequent calls with the same arguments, the function returns the result directly from the cache, avoiding repeated calculation.
Basic Memorization Implementation
function memoize(fn) { const cache = {}; return function(...args) { const key = JSON.stringify(args); // Cria uma chave única para os argumentos if (cache[key]) { console.log("Resultado em cache"); return cache[key]; // Retorna o valor armazenado no cache } const result = fn(...args); // Calcula o valor cache[key] = result; // Armazena o resultado no cache return result; }; }
Example of use:
function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); } const memoizedFactorial = memoize(factorial); console.log(memoizedFactorial(5)); // Calcula e armazena em cache console.log(memoizedFactorial(5)); // Recupera do cache
Benefits of Memorization
Summary
Memorization in JavaScript is a powerful technique for improving code efficiency and accelerating performance in repetitive, computationally expensive operations.
The above is the detailed content of Memorization in JavaScript. For more information, please follow other related articles on the PHP Chinese website!