memoization缓存优化

当请求或计算时,如果每次都进行重新请求或计算,非常损耗CPU性能,因此可以通过缓存将之前的记录保存下来,当请求某已经请求过的资源时,就可以直接使用缓存了。

封装如下:

function memoize(fn){
    return function(){
        var args = Array.prototype.slice.call(arguments)
        var cache = cache || {}
        return cache[args] ? cache[args] : fn.apply(this, args)
    }
}        

当然,可以直接向Function的原型上添加该方法

function memoize(){
    var self = this
    return function(){
        var args = Array.prototype.slice.call(arguments)
        var cache = cache || {}
        return cache[args] ? cache[args] : self(args)
    }
} 

 当然,这样操作并不适合所有场景。一般在纯函数中使用,是一种空间换时间的做法

原文地址:https://www.cnblogs.com/ashen1999/p/12955447.html