`
sevenduan
  • 浏览: 12104 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
最近访客 更多访客>>
社区版块
存档分类
最新评论

Efficient JavaScript Coding Convention[待续]

阅读更多
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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics