2025-08-25 模拟面试(七)

  1. 实现一个函数 memoize,支持缓存函数执行结果(考虑参数序列化、过期时间等)

memoize 是一个非常实用的性能优化工具,常见于: React 中的 useMemo / useCallback Lodash 的 _.memoize API 请求缓存 复杂计算缓存(如斐波那契) 掌握它的实现原理,有助于你写出更高效、更智能的前端代码。

缺点可能有以下几点:

  1. 如果是对象等数据被缓存过多则可能会导致内存泄露
  2. 如果调用者不知道被缓存可能调试困难
  3. 参数序列化的问题
  4. 如果考虑全面,则代码可能过于复杂,反而得不偿失
// 存储函数
function memoize(fn, resolver = JSON.string, time) {
  const cache = new Map();

  return function (...args) {
    const key = resolver();

    const now = +new Date();

    if (cache.has(key)) {
      const valObj = cache.get(key);
      if (time) {
        cache.delete(key);
      } else {
        return valObj.value;
      }
    }

    const result = fn.apply(this, args);

    cache.set(key, { value: result, stmp: now });

    return result;
  };
}

// 计算量大的函数
function count(number) {
  let result = 0;
  for (let index = 0; index < number; index++) {
    result += index;
  }
  return result;
}

const memoizedCalc = memoize(count);

// 第一次计算后会把结果缓存起来,后面如果继续调用就可以直接return结果了。
memoizedCalc(1000000);
memoizedCalc(1000000);

results matching ""

    No results matching ""