Efficient JavaScript coding
1, 盡可能選擇高效的method
e.g.
如果沒有必要,可以不用regular expression
String.indexOf, String.lastIndexOf > String.match, String.search, String.replace
2, 面對large loop就要斤斤計較
2.1 Create once, use repeatedly
for( var i = 0, oNode; oNode = oElement.childNodes[i]; i++ ) {
if( oNode.nodeValue.match(/^\s*extra.*free/g) ) {
//this creates the expression
//it will be cached and re-used next time through the loop
}
}
for( var i = 0, oNode; oNode = oElement.childNodes[i]; i++ ) {
if( oNode.nodeValue.match(new RegExp(“^\s*extra.*free”,”g”)) ) {
//this will always create a new copy of the expression,
//and is generally much slower than creating static expressions.
}
}
2.2 Referencing element once, use repeatedly
var _table =$("#tableId")
for (var index in json) {
otherFun(_table, json[index]);
};
3 eval is evil
Eval 或者 new Function() 執行時,瀏覽器先創建整個scripting環境(就像一個新頁面),導入scope chain中所有變量,執行script,gc, 最后導出所有變量到當前環境。(in a word, cost much)另外,js engine還不能對它們進行cache優化。
4 less is more
Less code, short naming
Only add event listener what you need
5 do less
Take a short circuit
e.g
var logger=window.console && window.console.dir
var logger=window.console || {}
less XHR calling
e.g. enable cache for the same request
6 Reduce reflow
每當添加element到document里,browser就會reflow整個頁面去計算如何重新定位和渲染。
7,cache
Enable cache for duplicated XHR calling
Enable cache for js script file, so move out jscript from jsp to js file.
Reference:
http://slowjavascript.com/JavaScript_Performance_Rocks_Checklist.pdf
已有 0 人發表留言,猛擊->>這里<<-參與討論
JavaEye推薦
文章來源:
http://sevenduan.javaeye.com/blog/505272