js物件導向編程:資料的緩衝
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和傳遞的參數