4種方法 對比:
private void Form2_Load(object sender, EventArgs e)<br /> {<br /> string str = "這心情就像那 低熱量的雪糕,淡淡的不夠呼味道,總覺得少了什麼";<br /> string[] a;</p><p> skyvu.Tester tester = new skyvu.Tester(100000);<br /> richTextBox1.AppendText( tester.Run("ToCharArray", delegate()<br /> {<br /> a = SplitToArray(str);</p><p> }));</p><p> richTextBox1.AppendText(tester.Run("StringIndex", delegate()<br /> {<br /> a = SplitToArray2(str);</p><p> }));</p><p> richTextBox1.AppendText(tester.Run("Regex", delegate()<br /> {<br /> a = SplitToArray3(str);</p><p> }));</p><p> richTextBox1.AppendText(tester.Run("Linq", delegate()<br /> {<br /> a = SplitToArray4(str);</p><p> }));</p><p> }</p><p> public string[] SplitToArray(string str)<br /> {<br /> char[] chs = str.ToCharArray();<br /> string[] sArr = new string[chs.Length];<br /> for (int i = 0; i < chs.Length; i++)<br /> {<br /> //sArr[i] = chs[i].ToString();<br /> sArr[i] = new string(chs[i],1);<br /> }<br /> return sArr;<br /> }</p><p> public string[] SplitToArray2(string str)<br /> {<br /> string[] sArr = new string[str.Length];<br /> for (int i = 0; i < str.Length; i++)<br /> {<br /> sArr[i] = str[i].ToString();<br /> }<br /> return sArr;<br /> }<br /> //private static Regex regSplit = new Regex("(?!^|$)",RegexOptions.Compiled);//沒有明顯的提升<br /> public string[] SplitToArray3(string str)<br /> {<br /> return Regex.Split(str, "(?!^|$)");<br /> //return regSplit.Split(str);<br /> }</p><p> public string[] SplitToArray4(string str)<br /> {<br /> return (from ch in str select ch.ToString()).ToArray();<br /> }
Tester類源碼
結果:
ToCharArray : 128 ms<br />StringIndex : 135 ms<br />Regex : 2480 ms<br />Linq : 469 ms