基础学习: memoize/memo
一个提升性能的函数
含义
记忆化函数(Memoization)的实现。记忆化是一种优化技术,用于存储函数的结果,以避免重复计算。
实现
- 指定一个字符串类型的 key用于cache
- 如果 key不变,就直接返回结果
function memoize(fn) {
  const cache = {}; // 创建一个缓存对象,用于存储计算结果
  return function (arg) {
    if (cache.hasOwnProperty(arg)) {
      // 如果缓存中已经有这个参数的计算结果
      return cache[arg]; // 直接返回缓存的结果
    }
    const result = fn(arg); // 否则,调用原始函数进行计算
    cache[arg] = result; // 将计算结果存入缓存对象
    return result; // 返回计算结果
  };
}改进
- key 可以用函数来指定,理论上是任意类型
- maxCacheSize: 指定上限,节省内存
function memoize(fn, keyGenerator = JSON.stringify) {
  const cache = {};
  return function (...args) {
    const key = keyGenerator(args);
    if (cache.hasOwnProperty(key)) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}function memoize(fn, keyGenerator = JSON.stringify, maxCacheSize) {
  const cache = {};
  const keys = [];
  return function (...args) {
    const key = keyGenerator(args);
    if (cache.hasOwnProperty(key)) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    keys.push(key);
    if (maxCacheSize && keys.length > maxCacheSize) {
      const oldestKey = keys.shift();
      delete cache[oldestKey];
    }
    return result;
  };
}cheatsheet
| 用法 | 说明 | 
|---|---|
| 缓存同步结果 |  | 
| 缓存异步结果 |  | 
实际应用
- httpSchema 中的 cache配置