求阶乘
一般求阶乘的方法
function factorial(n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1)
}
console.time("factorial");
factorial(3000)
console.timeEnd("factorial");
可以看到直接运行时间大概在0.3s左右
通过hash表来进行缓存
let cache = {};
function getCache(n) {
if (cache[n]) return cache[n];
if (n == 0 || n == 1) return (cache[n] = 1);
return (cache[n] = n * getCache(n - 1));
}
console.time("getCache-first");
getCache(3000)
console.timeEnd("getCache-first");
console.time("getCache-second");
getCache(2000)
console.timeEnd("getCache-second");
可以发现第一次调用时0.9s 第二次调用就是0.01s
高阶记忆函数
将该过程进行抽象化成一个函数让其拥有通用性
function memorize(fn) {
let cache = {};
return function () {
let key = fn.name + '_' + [].join.call(arguments, ','); //函数名和参数进行拼接
// console.log(key, arguments);
return (cache[key] = cache[key] || fn.apply(this, arguments));
}
}
let memorizeFactory = memorize(factorial);
console.time("memorizeFactory-first");
memorizeFactory(3000)
console.timeEnd("memorizeFactory-first");
console.time("memorizeFactory-second");
memorizeFactory(3000)
console.timeEnd("memorizeFactory-second");
实现缓存
import {api} form "./utils";
const cache = {};
const request = async (url) => {
if(cache[url]){
return cache[url]
}
const response = await api(url);
cache[url] = response;
return response
}