作者chhuang (Rolling Star)
看板C_Sharp
標題Re: [問題] 問個簡單問題~~~
時間Mon May 14 13:36:01 2007
※ 引述《GreatShot (我要拿Ph.D.!!!)》之銘言:
: string[] stringArray = Regex.Split(source,regexpression);
: 一行搞定
: enjoy it ^^
: 但是效率我就不保證了...有空作個實驗吧~~
好像效率會差了一些,而且切出來的陣列內容還需要修飾一下。
首先,寫了 Class T 包含靜態方法 ToStringArray。
為的是與同是靜態方法 Rexgex.Split(source, "") 作比較。
然後,利用 Stopwatch 計算 100 萬次各自花的時間。
最後,將 "100 萬次所需時間" 與 string[] target 內容列出來。
程式碼如下:
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
internal class T
{
public static string[] ToStringArray(string source)
{
char[] sourceChars = source.ToCharArray();
string[] target = new string[sourceChars.Length];
for (int i = 0; i < sourceChars.Length; i++)
{
target[i] = sourceChars[i].ToString();
}
return target;
}
}
internal class Program
{
private static void Main(string[] args)
{
string source = "1234567";
string[] target = null;
Stopwatch sw = null;
sw = Stopwatch.StartNew();
for (int i = 1; i <= 1000000; i++)
{
target = Regex.Split(source, "");
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
foreach (string s in target)
{
Console.WriteLine("--- " + s + " ---");
}
target = null;
sw = null;
sw = Stopwatch.StartNew();
for (int i = 1; i <= 1000000; i++)
{
target = T.ToStringArray(source);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
foreach (string s in target)
{
Console.WriteLine("--- " + s + " ---");
}
}
}
執行結果:
21412
=== ===
=== 1 ===
=== 2 ===
=== 3 ===
=== 4 ===
=== 5 ===
=== 6 ===
=== 7 ===
=== ===
1028
=== 1 ===
=== 1 ===
=== 2 ===
=== 3 ===
=== 4 ===
=== 5 ===
=== 6 ===
=== 7 ===
--
http://blog.roodo.com/chhuang
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.30.74.102
→ chhuang:學 C# 沒有多久...測試方式有錯請各位糾正....^^ 05/14 13:37
推 rayhill:有趣的實驗@@,會是參數傳遞產生的差異嗎?還有split內部的 05/15 00:12
→ rayhill:運作,來這果然可以學好多東西 05/15 00:14