Efficient JavaScript coding
1, 盡可能選擇高效的method
e.g.
如果沒有必要,可以不用regular expression
String.indexOf, String.lastIndexOf > String.match, String.search, String.replace
2, 面對large loop就要斤斤計(jì)較
2.1 Create once, use repeatedly
2.2 Referencing element once, use repeatedly
3 eval is evil
Eval 或者 new Function() 執(zhí)行時(shí),瀏覽器先創(chuàng)建整個(gè)scripting環(huán)境(就像一個(gè)新頁面),導(dǎo)入scope chain中所有變量,執(zhí)行script,gc, 最后導(dǎo)出所有變量到當(dāng)前環(huán)境。(in a word, cost much)另外,js engine還不能對它們進(jìn)行cache優(yōu)化。
4 less is more
Less code, short naming
Only add event listener what you need
5 do less
Take a short circuit
e.g
less XHR calling
e.g. enable cache for the same request
6 Reduce reflow
每當(dāng)添加element到document里,browser就會(huì)reflow整個(gè)頁面去計(jì)算如何重新定位和渲染。
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 人發(fā)表留言,猛擊->>這里<<-參與討論
JavaEye推薦
文章來源:http://sevenduan.javaeye.com/blog/505272
1, 盡可能選擇高效的method
e.g.
如果沒有必要,可以不用regular expression
String.indexOf, String.lastIndexOf > String.match, String.search, String.replace
2, 面對large loop就要斤斤計(jì)較
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() 執(zhí)行時(shí),瀏覽器先創(chuàng)建整個(gè)scripting環(huán)境(就像一個(gè)新頁面),導(dǎo)入scope chain中所有變量,執(zhí)行script,gc, 最后導(dǎo)出所有變量到當(dāng)前環(huán)境。(in a word, cost much)另外,js engine還不能對它們進(jìn)行cache優(yōu)化。
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
每當(dāng)添加element到document里,browser就會(huì)reflow整個(gè)頁面去計(jì)算如何重新定位和渲染。
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 人發(fā)表留言,猛擊->>這里<<-參與討論
JavaEye推薦
- 【杭州】高薪招聘java高級(jí)工程師,項(xiàng)目經(jīng)理,架構(gòu)師
- 上海30-40萬年薪招聘金融咨詢顧問
- 參加贏在淘寶,獲取開放平臺(tái)高級(jí)權(quán)限
- 【杭州】高薪招聘控件高級(jí)開發(fā)工程師(9w-18w年薪)
文章來源:http://sevenduan.javaeye.com/blog/505272