如何在 JavaScript 中使用存储器提高计算速度?
存储器是一种优化方法 ,对耗时的递归运算,漫长的查找运算的结果进行缓存,使运行时间最小化,简单讲就是把函数的计算结果缓存起来。这个对于计算量大的递归调用,可以加快速度。
特性与用途
- 应该主要用于加速执行缓慢、成本高或耗时的函数调用
- 加快了后续调用的速度,在相同的情况下且需要同一函数的多次调用时,最好使用它
一个简单、面向对象的例子如下:
class MyObject {
constructor(data) {
this.data = data;
this.data[this.data.length - 2] = { value: 'Non-empty' };
}
firstNonEmptyItem() {
return this.data.find(v => !!v.value);
}
firstNonEmptyItemMemo() {
if (!this.firstNonEmpty)
this.firstNonEmpty = this.data.find(v => !!v.value);
return this.firstNonEmpty;
}
}
const myObject = new MyObject(Array(2000).fill({ value: null }));
for (let i = 0; i < 100; i ++)
myObject.firstNonEmptyItem(); // ~4000ms
for (let i = 0; i < 100; i ++)
myObject.firstNonEmptyItemMemo(); // ~70ms
上面的例子展示了一种在类中实现存储器的方法,复用性比较差,也没有考虑传参。我们可以用一个函数式的方法,这个方法使用Map来存储不同的值:
const memoize = fn => new Proxy(fn, {\
cache: new Map(),\
apply (target, thisArg, argsList) {\
let cacheKey = argsList.toString();\
if(!this.cache.has(cacheKey))\
this.cache.set(cacheKey, target.apply(thisArg, argsList));\
return this.cache.get(cacheKey);\
}\
});\
\
const fibonacci = n => (n <= 1 ? 1 : fibonacci(n - 1) + fibonacci(n - 2));\
const memoizedFibonacci = memoize(fibonacci);\
\
for (let i = 0; i < 100; i ++)\
fibonacci(30); // ~5000ms\
for (let i = 0; i < 100; i ++)\
memoizedFibonacci(30); // ~50ms\
- 如果这些方法能解决你工作中所遇到的一些问题,赶快点赞收藏关注吧,后续本号会分享更多实用的前端代码片段