七段

无论怎样,请让我先感谢一下国家。

BlogJava 首页 新随笔 联系 聚合 管理
  35 Posts :: 2 Stories :: 7 Comments :: 0 Trackbacks
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
posted on 2009-10-31 14:49 sevenduan 阅读(170) 评论(0)  编辑  收藏 所属分类: JavaScript

只有注册用户登录后才能发表评论。


网站导航: