Table of Contents
What is the main purpose of using memory in JavaScript?
How does memory work in JavaScript?
Can you provide an example of a memorized function in JavaScript?
Is there any limitations or disadvantages of using memory in JavaScript?
Can I use memorization for all types of functions in JavaScript?
How to memorize functions with multiple parameters in JavaScript?
Is there any library or tool that can help memorize in JavaScript?
How to clear cache in memory function?
Can memory be used in JavaScript frameworks such as React?
How is memory in JavaScript compared to other optimization techniques?
Home Web Front-end JS Tutorial Implementing Memoization in JavaScript

Implementing Memoization in JavaScript

Feb 26, 2025 am 01:50 AM

Implementing Memoization in JavaScript

Core points

  • Memorization is a programming technique that improves the performance of a function by caching the results of previous calculations of a function. This is especially useful for recursive and mathematical functions that often use the same parameters.
  • Implementing memory involves using caches indexed by the input parameters by the function. If the parameter exists in the cache, the cache value is returned; otherwise, the function is executed and the result is added to the cache.
  • When memorizing is used for functions with multiple parameters, multidimensional cache can be used, or all parameters can be combined to form a single index. Object parameters should be stringified before being used as indexes.
  • Memorization has certain limitations. It increases memory consumption and may not be suitable for functions that execute quickly or call low frequency. It can only be automated with references to transparent functions, i.e. its output depends only on its input and does not produce any side effects.

Programs often waste time calling functions that recalculate the same result repeatedly. This is especially true for recursive and mathematical functions. The Fibonacci number generator is a perfect example. A Fibonacci sequence is a series of integers starting with zero sums, where each value is the sum of the first two numbers in the sequence. According to this definition, the first ten Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. From a programming perspective, the Fibonacci numbers are usually calculated recursively using the following functions. This function works well for smaller "n" values. However, as "n" increases, performance drops rapidly. This is because the two recursive calls repeat the same work. For example, to calculate the 50th Fibonacci number, the recursive function must be called more than 40 billion times (40,730,022,147 to be exact)! To make matters worse, calculating the 51st figure requires repeating the work almost completely twice. If the function remembers what it calculated before, it can alleviate the problem of repeated work.

function fibonacci(n) {
  if (n === 0 || n === 1)
    return n;
  else
    return fibonacci(n - 1) + fibonacci(n - 2);
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Basics of Memorization

Memorization is a programming technique that attempts to improve the performance of a function by caching the results of a function's previous calculations. Because JavaScript objects behave like associative arrays, they are ideal for acting as caches. Each time the memory function is called, its parameters are used for index cache. If the data exists, it can be returned without executing the entire function. However, if the data is not cached, the function is executed and the result is added to the cache.

In the following example, the original Fibonacci function is rewritten to include memory. In this example, the self-executing anonymous function returns an internal function f() which is used as the Fibonacci function. When f() is returned, its closure allows it to continue accessing the "memo" object, which stores all its previous results. Each time f() is executed, it first checks whether the result of the current "n" value exists. If present, the cache value is returned. Otherwise, execute the original Fibonacci code. Note that "memo" is defined outside of f() so that it can retain its value in multiple function calls. Recall that the original recursive function was called more than 40 billion times before it could calculate the 50th Fibonacci number. By implementing memory, this number drops to 99.

function fibonacci(n) {
  if (n === 0 || n === 1)
    return n;
  else
    return fibonacci(n - 1) + fibonacci(n - 2);
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Processing multiple parameters

In the previous example, the function accepts a single parameter. This makes implementing caching quite simple. Unfortunately, most functions require multiple parameters, which complicates cached indexes. To memorize a function with multiple parameters, the cache must become multidimensional, or all parameters must be combined to form a single index.

In multidimensional methods, cache becomes the hierarchy of the object, not a single object. Each dimension is then indexed by a single parameter. The following example implements a multidimensional cache for the Fibonacci function. In this example, the function accepts an additional parameter "x" and it does nothing. Each time a function is called, the code checks whether the "x" dimension exists and initializes it if it does not exist. Since then, the "x" dimension is used to cache the "n" value. The result is that function calls fibonacci("foo", 3) and fibonacci("bar", 3) are not considered the same result.

var fibonacci = (function() {
  var memo = {};

  function f(n) {
    var value;

    if (n in memo) {
      value = memo[n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(n - 1) + f(n - 2);

      memo[n] = value;
    }

    return value;
  }

  return f;
})();
Copy after login
Copy after login
Copy after login
Copy after login

The alternative to multidimensional cache is a single cache object, which is indexed by a combination of all parameters of the function. In this method, the parameters are converted to an array and then used for the index cache. Each function has a built-in object named "arguments" that contains the passed in parameters. "arguments" is an object of type called an array object of class. It is similar to an array, but cannot be used for index cache. Therefore, it must first be converted to the actual array. This can be done using the array slice() method. The cache can then be indexed using array representations, as shown before. The following example shows how to achieve this. Note that the additional variable "slice" is defined as a reference to the array slice() method. By storing this reference, you can avoid repeated calculations of Array.prototype.slice() overhead. Then use the call() method to apply slice() to "arguments".

var fibonacci = (function() {
  var memo = {};

  function f(x, n) {
    var value;

    memo[x] = memo[x] || {};

    if (x in memo && n in memo[x]) {
      value = memo[x][n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(x, n - 1) + f(x, n - 2);

      memo[x][n] = value;
    }

    return value;
  }

  return f;
})();
Copy after login
Copy after login

Cache object parameters

The memory scheme introduced here does not handle object parameters well. When objects are used as indexes, they are first converted to string representations, such as "[object Object]". This causes multiple objects to be incorrectly mapped to the same cache location. This behavior can be corrected by stringifying object parameters before indexing. Unfortunately, this also slows down the memory process. The following example creates a general memory function that takes an object as an argument. Note that object parameters are stringified using JSON.stringify() to create cached indexes.

function fibonacci(n) {
  if (n === 0 || n === 1)
    return n;
  else
    return fibonacci(n - 1) + fibonacci(n - 2);
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Automatic memory

In all previous examples, the function is explicitly modified to add memory. Memorized infrastructure can also be implemented without modifying the functions at all. This is useful because it allows the function logic to be implemented separately from the memorized logic. This is done by creating a utility function that takes the function as input and applies it to memorizes it. The following memoize() function takes the function "func" as input. memoize() returns a new function that wraps the cache mechanism around "func". Note that this function does not handle object parameters. To process the object, a loop is needed that will check each parameter individually and stringify as needed.

var fibonacci = (function() {
  var memo = {};

  function f(n) {
    var value;

    if (n in memo) {
      value = memo[n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(n - 1) + f(n - 2);

      memo[n] = value;
    }

    return value;
  }

  return f;
})();
Copy after login
Copy after login
Copy after login
Copy after login

Limitations

When realizing memory, the following points must be remembered. First, by storing old results, the memorization function consumes extra memory. In the Fibonacci example, the extra memory consumption is unlimited. If memory usage is a problem, a fixed-size cache should be used. The overhead associated with memory may also make it unsuitable for functions that execute very quickly or have low frequency.

The biggest limitation of memory is that it can only be automatically applied to the

reference transparent functions. If the output of a function depends only on its input and does not produce any side effects, the function is considered reference-transparent. Calls that reference transparent functions can be replaced with their return value without changing the semantics of the program. The Fibonacci function is referenced transparent because it depends entirely on the value of "n". In the following example, the function foo() is not referenced transparent because it uses the global variable "bar". Since "bar" can be modified outside of foo(), there is no guarantee that the return value will remain unchanged for each input value. In this example, the two calls to foo() return values ​​2 and 3, even if the parameters passed to the two calls are the same.

var fibonacci = (function() {
  var memo = {};

  function f(x, n) {
    var value;

    memo[x] = memo[x] || {};

    if (x in memo && n in memo[x]) {
      value = memo[x][n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(x, n - 1) + f(x, n - 2);

      memo[x][n] = value;
    }

    return value;
  }

  return f;
})();
Copy after login
Copy after login

Things to remember

  • Memorization can potentially improve performance by caching the results of previous function calls.
  • The memory function stores a cache indexed by its input parameters. If the parameter exists in the cache, the cache value is returned. Otherwise, execute the function and add the newly calculated value to the cache.
  • Object parameters should be stringified before being used as indexes.
  • Memorization can be automatically applied to reference transparent functions.
  • Memorization may not be ideal for functions that are not called frequently or executed quickly.

FAQ on Memorizing in JavaScript (FAQ)

What is the main purpose of using memory in JavaScript?

Memorization is a programming technique used to optimize computer programs in JavaScript and other languages. This technique involves storing the results of expensive function calls and reusing them when the same input appears again. This can greatly improve the performance of the program by avoiding unnecessary calculations. It is especially useful in situations where recursive functions or functions that are repeatedly called with the same parameters.

How does memory work in JavaScript?

In JavaScript, memory works by creating a cache to store the results of function calls. When calling a function, the function first checks whether the result of the given input is already in cache. If so, the function returns the cached result instead of performing the calculation again. If the result is not in the cache, the function performs the calculation, stores the result in the cache, and returns the result.

Can you provide an example of a memorized function in JavaScript?

Of course, let's consider an example of a simple function that calculates the factorial of numeric. Without memory, the function looks like this:

function fibonacci(n) {
  if (n === 0 || n === 1)
    return n;
  else
    return fibonacci(n - 1) + fibonacci(n - 2);
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Using memory, we can optimize this function by storing the results of previous function calls:

var fibonacci = (function() {
  var memo = {};

  function f(n) {
    var value;

    if (n in memo) {
      value = memo[n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(n - 1) + f(n - 2);

      memo[n] = value;
    }

    return value;
  }

  return f;
})();
Copy after login
Copy after login
Copy after login
Copy after login

Is there any limitations or disadvantages of using memory in JavaScript?

While memorization can significantly improve the performance of JavaScript programs, it is not without its limitations. A major disadvantage of memory is that it can consume a lot of memory, especially when storing a lot of data in cache. If not managed properly, this can lead to performance issues. Furthermore, memory is only valid when the function is called with the same parameter multiple times. Memorization does not provide any performance benefits if the function input is always different.

Can I use memorization for all types of functions in JavaScript?

Memorization is most effective when used with pure functions. A pure function is a function that always returns the same result of the same input and does not produce any side effects. Memorizing the function may lead to unexpected results if it depends on an external state or has side effects. So while you can technically use memorization for any type of function in JavaScript, it is best for pure functions.

How to memorize functions with multiple parameters in JavaScript?

Implementing memory for a function with multiple parameters can be a bit complicated, but this is definitely possible. One way is to convert the arguments into strings that can be used as keys in the cache. Here is an example:

function fibonacci(n) {
  if (n === 0 || n === 1)
    return n;
  else
    return fibonacci(n - 1) + fibonacci(n - 2);
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Is there any library or tool that can help memorize in JavaScript?

Yes, there are libraries and tools that can help memorize in JavaScript. For example, the popular JavaScript utility library Lodash provides a _.memoize function that can easily memorize functions. Similarly, the Ramda library provides a R.memoizeWith function that allows you to specify custom cache key functions.

How to clear cache in memory function?

The cache in the memory function can be cleared by simply resetting the cache object. Here is an example:

var fibonacci = (function() {
  var memo = {};

  function f(n) {
    var value;

    if (n in memo) {
      value = memo[n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(n - 1) + f(n - 2);

      memo[n] = value;
    }

    return value;
  }

  return f;
})();
Copy after login
Copy after login
Copy after login
Copy after login

Can memory be used in JavaScript frameworks such as React?

Yes, memory is very useful in JavaScript frameworks such as React. For example, React provides a React.memo function that can be used to memorize components. This can help improve performance by preventing unnecessarily re-rendering of components.

How is memory in JavaScript compared to other optimization techniques?

Memorization is a powerful optimization technique, but it is not always the best solution. In some cases, other optimization techniques such as dejitter and throttling may be more suitable. The key is to understand the specific needs and constraints of the program and choose the right optimization technology.

The above is the detailed content of Implementing Memoization in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles