webVueBlog/Leetcode

24.什么是memoization

webVueBlog opened this issue · 0 comments

记忆化是一种编程技术,它试图通过缓存以前计算的结果来提高函数的性能。每次调用 memoized 函数时,它的参数都用于索引缓存。如果数据存在,则可以将其返回,而无需执行整个函数。否则执行该函数,然后将结果添加到缓存中。让我们举一个使用 memoization 添加函数的例子

const memoizAddition = () => {
  let cache = {};
  return (value) => {
    if (value in cache) {
      console.log("Fetching from cache");
      return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript  identifier. Hence, can only be accessed using the square bracket notation.
    } else {
      console.log("Calculating result");
      let result = value + 20;
      cache[value] = result;
      return result;
    }
  };
};
// returned function from memoizAddition
const addition = memoizAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached