JavaScript String match 和indexOf方法的性能测试


function add(str,count){
if(count && count>10){
count = 10;//count不可太大,否则浏览器会很容易崩溃
}
for(var i = 0;i < count;i++){
str = str+str;
}
return str;
}
var s = document.body.innerHTML;
//console.log(s.length);
s = add(s,10);
//console.log(s.length);
var start = (new Date()).getTime();
var match = s.match(/闲聊/gi); //去掉gi选项会快很多
console.log((new Date()).getTime()-start);
var start2 = (new Date()).getTime();
s.indexOf('闲聊');
console.log((new Date()).getTime()-start2);

[b]测试结果[/b]:
在chrome和firefox下indexOf 比match快很多。复杂模式下match应该会快一些。测试案例不完善,不能说明什么。不过平时代码中个人还是使用match多一些,因为语义上更清晰。

[url]http://userjs.org/help/tutorials/efficient-code#stringmatch[/url]这篇文章解说的不错,该作者推荐indexOf:
[quote]
String matching

If you need to search a within one string to see if it contains another string, there are two basic ways to do it. The first is to use 'indexOf' to find the position of the substring within the string. The second is to use 'match' or an equivalent method to find if a regular expression pattern can be found in the string.

All string matching techniques are very fast, but they should be used carefully to avoid making them wasteful. In general, with very simple string matches in Opera, stringObject.indexOf is faster than stringObject.match. If searching for simple string matches, indexOf should be used instead of regular expression matching wherever possible.

You should avoid matching against very long strings (10KB+) unless you absolutely have to. If you are certain that the match will only occur in a specific portion of the string, take a substring, and compare against that, instead of the entire string.

Using regular expressions with large numbers of wildcards will make string matching noticably slower. Repeatedly replacing substrings is also costly, and if possible try to reduce the number of replace commands you use, and try to optimise into fewer, more efficient replace commands. In many cases, string replacement performed against the page's own scripts would be better done by using opera.defineMagicFunction or defineMagicVariable to override a variable. If possible, use these instead. There is no single rule to this, and each script will need to be dealt with on an indiviual basis.
[/quote]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值