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]
本文通过一个简单的JavaScript函数展示了在不同浏览器环境下使用indexOf与match进行字符串匹配的速度对比。测试结果显示,在简单模式下indexOf通常比match更快。
614

被折叠的 条评论
为什么被折叠?



