函数缓存

为了讲明白这个概念,假设你在开发一个天气app。开始你不知道怎么做,正好有一个npm包里有一个getChanceOfRain的方法可以调用:

import { getChangeOfRain } from 'magic-weather-calculator';

function showWeatherReport() {
  let result = getChangeOfRain();    // 这里调用
  console.log('The change of rain tomorrow is: ', result);
}
复制代码

只是这样会遇到一个问题。无论你做什么,只要调用这个方法就会消耗100毫秒。所以,如果某个用户疯狂点击“显示天气”按钮,每次点击app都会有一段时间没有响应。

showWeatherReport(); // 触发计算
showWeatherReport(); // 触发计算
showWeatherReport(); // 触发计算
复制代码

这很不理性。在实际开发中,如果你已经知道结果了,那么你不会一次一次的计算结果。重用上次的结果才是上佳选择。这就是函数缓存。函数缓存也就是缓存函数的结算结果,这样就不需要一次一次的调用函数

在下面的例子里,我们会调用memoizedGetChangeOfRain()。在这个方法里我们会检查一下是否已经有结果了,而不会每次都调用getChangeOfRain()方法:

import { getChangeOfRain } from 'magic-weather-calculator';

let isCalculated = false;
let lastResult;

// 添加这个方法
function momoizedGetChangeOfRain() {
  if (isCalculated) {
    // 不需要在计算一次
    return lastResult;
  }
  
  // 第一次运行时计算
  let result = getChangeOfRain();
  
  lastResult = result;
  isCalculated = true;
  
  return result;
}

function showWeatherReport() {
  let result = momoizedGetChangeOfRain();
  console.log('The chance of rain tomottow is:', result);
}




复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享