Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

24.什么是memoization #41

Open
webVueBlog opened this issue Jun 6, 2022 · 0 comments
Open

24.什么是memoization #41

webVueBlog opened this issue Jun 6, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

记忆化是一种编程技术,它试图通过缓存以前计算的结果来提高函数的性能。每次调用 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant