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);
テスト結果:
chromeとfirefoxの下でindexOfはmatchよりずっと速いです.複雑なモードでは、マットの方が速いはずです.テストケースが不完全です.何を説明することができません.しかし、通常のコードの中では、個人はまだmatchを多く使っています.意味がもっとはっきりしています.
http://userjs.org/help/tutorials/efficient-code#stringmatchこの文章はよく解説されています.この作者のオススメはindexOfです.
参照
String matching
If you need to search a within one string to see if it contains another string、there re re two baic ways to do it.The first is to use'indexOf'to find the position of the substring within the string.The second is the the the ficond ist is the the the the the the the the fident the the the the firevent of the the string.
All string matching techniques ararevery fast、but they shoud be used carefully to avoid making them wasteful.In general、with very simple ststinininininininininininininininininstststststinininininininininininininininininininininstststststststststststststeeeeeeeededededededededededededededededeststststststststinininininininininininininininininininininininininininininininininininininininininininininible.
You shoud avoid matching against very stings(10 KB+)unless you absolutiely have to.If You are certain the match will only occur in a specific potion of the string,tae substring,and compre ainst aint
Using reglar expressions with large numbers of wildcards will make string make string make string noticably slower.Repeatly replace substreings s s costinity,and ifessible to reduce the number of place commandstring replocment performed against the page's own scripts would be better done by using opera.defineMagic Function or definemagic Veriable to overrida variable.If possible、use these instead.The is sigland.The sigrule.