Home  >  Article  >  Web Front-end  >  Memorization in JavaScript

Memorization in JavaScript

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 07:36:02255browse

Memorização em JavaScript

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

  • Processing Reduction: Avoids repeated calculations, which improves performance.
  • Ideal for Recursive Functions: Speeds up the processing of functions that need to be called multiple times with the same values.
  • Efficient on Pure Functions: Memorization works best when the function returns the same value for the same arguments. Common Applications of Memorization
  • Mathematical Calculations: Like factorial, Fibonacci, etc.
  • API Calls: Prevents duplicate API calls with the same parameters.
  • High Cost Operations: Data processing and complex manipulations.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn