js也可以通过缓存数据,来加快处理速度。在必要的时候使用空间还换取时间还是值得的。例如需要很长时间才能完成的计算,就可以把计算结果缓存到客户端,以后就可以直接使用缓存的计算结果,不在重复计算。
1简单函数的计算结果的缓存 2递归函数的计算结果的缓存 3Ajax读取数据的缓存
1简单函数的计算结果的缓存
例如:
//共用函数,封装内部调用,缓存计算结果
function memorize(f)
{
var cache={};
return function(){
var key=arguments.length+Array.prototype.join.call(arguments,",");//参数长度和参数作为属性值
if(key in cache) //存在则直接读取缓存数据
{
return cache[key];
}
else
{
return cache[key]=f.apply(this,arguments);//不存在,则计算,并缓存计算结果
}
}
}
具体使用
//模拟需要很长时间的计算的函数
function TestFunction(x)
{
return x*x;
}
//测试,调用
function test(){
var t=memorize(TestFunction);
var k=t(6);// 第一次调用需要计算
var k2=t(6);//第二次直接读取换缓存,不在计算
alert(k2);
}
2 递归函数的计算结果的缓存
具体使用
function test2(){
var t=memorize( function(x){//递归函数计算X的阶乘
if(x<=0){return 1;}
else{ return x*t(x-1) }
});
var k=t(6);//缓存了6至1的阶乘
var k2=t(7);//只需要调用一次,计算6阶乘时使用了缓存
alert(k2);
}
3Ajax读取数据的缓存
对于Ajax的缓存也可以使用类似的方式,其实还是从https://github.com/devbridge/jQuery-Autocomplete中学习来的
原理其实和上边的是一样的。
核心部分整理如下:
function Autocomplete()
{
this.cachedResponse = {};//缓存的数据保存的容器
this.badQueries = [];//查询后,没有满足条件的查询
}
Autocomplete.prototype.clearCache = function ()//清空缓存
{
this.cachedResponse = {};
this.badQueries = [];
},
Autocomplete.prototype.getSuggestions=function (q) {//读取数据
var response,
that = this,
options = that.options,
serviceUrl = options.serviceUrl,
data,
cacheKey;
options.params[options.paramName] = q;
data = options.ignoreParams ? null : options.params;
cacheKey = serviceUrl + '?' + $.param(data || {});//缓存的键是URL和传递的参数组成
response = that.cachedResponse[cacheKey];//获取缓存的数据
if (response && $.isArray(response.suggestions)) {//如果有缓存
that.suggestions = response.suggestions;
that.suggest();
} else if (!that.isBadQuery(q)) {// 没有查询过,而且不是查询后没有满足条件的查询
that.currentRequest = $.ajax({//没有缓存通过Ajax读取数据
url: serviceUrl,
data: data,
type: options.type,
dataType: options.dataType
}).done(function (data) {
that.currentRequest = null;
that.processResponse(data, q, cacheKey);//缓存数据
options.onSearchComplete.call(that.element, q);
}).fail(function (jqXHR, textStatus, errorThrown) {
options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
});
}
}
可以看到核心还是和上边的情况是一样的,只是缓存数据的键变成了Ajax的URL和传递的参数