函数记忆是一种编程技巧,通过牺牲算法的空间复杂度以换取更优的时间复杂度
- 定义: 若传递的参数一致,则通过缓存读取存取计算结果的一种编程技巧
- 实现: 借助map对象、JSON.stringify()、闭包包装传递的函数,使其具有函数记忆的特性
const memorize = (cb) => {
const cache = new Map();
return function() {
const key = JSON.stringify(arguments);
if (cache.has(key)) {
return cache.get(key)
} else {
const result = fn(...arguments);
cache.set(key, result);
return result;
}
}
}
- 注意: 如果不存在大量可能的重复计算,使用函数记忆只会让计算更加低效