Memoization of JavaScript

Introduction to JavaScript memory

Memoization is a technique that allows you to greatly speed up applications.

Although I marked this article as "JavaScript", this is not a technology unique to JavaScript, because I will provide some JS examples.

Memoization is the act of storing the function in the function itself after it is run after the function is called. The next time we call this function, it will not perform "normal" execution, but just return the stored result.

it isCache, for function.

Why is this useful?

Suppose our function takes 1 second to run, and caching can speed up the process to 2 milliseconds. There are obvious gains here.

It sounds cool. Where is the catch?

If the result of calling a function with the same parameter set results in the same output, the memory is valid. In other words, the function must bepure. Otherwise, the cached result will be meaningless.

Therefore, it is impossible to optimize database queries, network requests, write files and other impure operations through remarks. For these, you will need to find other ways to optimize them. Or just living in an inefficient environment, which is sometimes inevitable.

Let's create an example:

// Calculate the factorial of num
const fact = num => {
  if (!fact.cache) {
    fact.cache = {}
  }
  if (fact.cache[num] !== undefined) {
    console.log(num + ' cached')
    return fact.cache[num];
  } else {
    console.log(num + ' not cached')
  }
  fact.cache[num] = num === 0 ? 1 : num * fact(num - 1)
  return fact.cache[num]
}

Calculate the factorial of a number. the first timefact()Run and it will create acacheThe object attribute of the function itself is used to store the calculation result.

Every time we call, if we arecacheObject, we perform calculations. Otherwise, we just return it.

Try to run it. I made Codepen to make it easy to test,document.write()Print to HTML page (the first time I usedocument.write()Old, but useful this time).

Look at the penDecomposition example factorialBy Flavio Copes (@flaviocopes) InCipher pen.

Tech Wiki Online!