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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值