关于javascript:函数缓存

在任何一个语言中,如果要一段程序计算量比拟大、执行工夫比拟长,咱们能够应用缓存机制将其后果保留下来,待一下次执行雷同的程序时,能够去保留的后果中间接获取,而无需再次计算。

在JavaScript中的实现如下


let cache = {};
function compute(a){
    let result;
    let key = a.toString();
    if(cache[a]){
        result = cache[a];
    }else{
        cache[key] = longTime(a);
    }
    return result;
    
}

咱们也能够将cache对像附加到函数上,这里提供一种简略的写法,基本原理还是从cache中取后果。

let cache = {};
function compute(a){
    let result;
    let key = a.toString();
    if(this.cache[a]){
        result = this.cache[a];
    }else{
        this.cache[key] = longTime(a);
    }
    return result;
}
compute.prototype.cache = cache;
new compute('test');

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理