请教个问题,计算一个数字的数列是要很长时间的,如下函数:
function res(n){
return n < 2 ? n : res(n - 1) + res(n - 2);
}
var start = new Date();
console.log(res(43));
console.log(new Date()-start+'ms');
Chrome执行结果如下:
433494437
8358ms
但是下面的函数res_1在没有经过缓存计算结果的前提下也能瞬间出结果,这是什么原理?
function res_1(n){
if(!res_1.cache[n]){
return res_1.cache[n] = n < 2 ? n : res_1(n - 1) + res_1(n - 2);
}
return res_1.cache[n];
}
res_1.cache = {};
var start = new Date();
console.log(res_1(43));
console.log(new Date()-start+'ms');
Chrome执行结果如下:
433494437
0ms
计算45的数列:
start = new Date();
console.log(res_1(45));
console.log(new Date()-start+'ms');
结果如下,未经过缓存
1134903170
0ms
而用res函数计算45的数列,要25468ms
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
可是res_1的计算过程中在一直做缓存啊,你为什么说没做缓存。