這篇文章記錄一次失败的優化嘗試,以及從失敗中得到的真正結論。(這並不代表 jQuery 的效能表現優越,而是說明它是一個相對封閉的庫,難以從外部介入做本質優化。)
靈感來自資料庫優化的一句老話:「把大量操作放進一個事務一起提交,能有效提升效率」。雖然並不清楚背後的確切原因,但「事務」這個概念替我指了方向(後來證明是錯的方向)。
於是打算把「事務」引入 jQuery:透過「開啟」與「提交」事務,從外部減少 each 的迴圈次數。
眾所周知,jQuery 的 DOM 操作以「get all, set first」為準則,其中設定屬性與樣式的操作幾乎都要對選出的元素做一次遍歷,而 jQuery.access 就是核心:
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn(
elems[i],
key,
exec ? value.call(elems[i], i, fn(elems[i], key)) : value,
pass
);
}
return elems;
}
jQuery.fn.css 就是這樣把工作轉包的:
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) { return this; }
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined
? jQuery.style( elem, name, value )
: jQuery.css( elem, name );
});
};
因此下面這段程式,若選到的 div 有 5000 個,就要遍歷 10000 次節點:
jQuery('div').css('height', 300).css('width', 200);
我的想法是:在一個「事務」中把操作先記下來,等「提交」時統一套用,就能把 10000 次節點存取壓到 5000 次,理論上等同效能提升一倍。
提供兩個函式:
實作步驟:建立事務物件並複製 jQuery.fn 上的所有方法;呼叫方法時把「方法名 + 參數」推進佇列;提交時對選到的元素做一次遍歷,對每個節點依序套用佇列中的所有方法。
var slice = Array.prototype.slice;
jQuery.fn.begin = function() {
var proxy = { _core: c, _queue: [] }, key, func;
// 複製 jQuery.fn 上的方法
for (key in jQuery.fn) {
func = jQuery.fn[key];
if (typeof func == 'function') {
// for 迴圈會導致 key 永遠是最後一次的值,
// 因此必須用閉包保住每次的 key(LIFT 效應)
(function(key) {
proxy[key] = function() {
this._queue.push([key, slice.call(arguments, 0)]); // 只進佇列,不執行
return this;
};
})(key);
}
}
proxy.commit = jQuery.fn.commit; // 避免 commit 本身被攔截
return proxy;
};
jQuery.fn.commit = function() {
var core = this._core, queue = this._queue;
core.each(function() { // 只跑一個 each 迴圈
var i = 0, item, jq = jQuery(this);
for (; item = queue[i]; i++) {
jq[item[0]].apply(jq, item[1]); // 對每個節點套用佇列中的所有方法
}
});
return this.c;
};
<div id="container"></div> 中放入 5000 個 div。$('#container>div') 選取這 5000 個元素。randomColor)與 800px 以內的隨機寬度(randomWidth)。四種寫法:
// 正常使用法
$('#container>div')
.css('background-color', randomColor)
.css('width', randomWidth);
// 單次循環法
$('#container>div').each(function() {
$(this).css('background-color', randomColor).css('width', randomWidth);
});
// 事務法
$('#container>div')
.begin()
.css('background-color', randomColor)
.css('width', randomWidth)
.commit();
// 物件賦值法
$('#container>div').css({
'background-color': randomColor,
'width': randomWidth
});