四種方法統計字符串的行數和執行時間比較
我需要統計一下字符串的行數,因此我就寫了一個超級沒有技術含量的蠻力方法來統計了。
- staticlongLinesCount(strings)
- {
- longcount = 0;
- intposition = 0;
- while((position = s.IndexOf(' ', position)) != -1)
- {
- count++;
- position++; //Skip this occurance!
- }
- returncount;
- }
這個函數他呀,運行正常,寫起來也快。
但是,我就像啊,這是不是也太沒有技術含量了,難道就沒有其他方法了?
當然有,我想出了兩種方法:正則和Linq,我把這些方法都寫出來
- staticlongLinesCountIndexOf(strings)
- {
- longcount = 0;
- intposition = 0;
- while((position = s.IndexOf(' ', position)) != -1)
- {
- count++;
- position++; //Skip this occurance!
- }
- returncount;
- }
- staticRegex r = newRegex(" ", RegexOptions.Multiline);
- staticlongLinesCountRegex(strings)
- {
- MatchCollection mc = r.Matches(s);
- returnmc.Count;
- }
- staticlongLinesCountLinq(strings)
- {
- return(fromch ins
- wherech== ' '
- selectch).Count();
- }
- staticlongLinesCountSplit(strings)
- {
- return(s.Split(newchar[] { ' '})).Length;
- }
然后呢,我又寫了一個快速但混亂的毫無技術含量的測試程序來測試正確性
- strings = File.ReadAllText(@"D:TempMyLargeTextFile.txt");
- longindex = LinesCountIndexOf(s);
- longregex = LinesCountRegex(s);
- longlinq= LinesCountLinq(s);
- Console.WriteLine("{0}:{1}:{2}", index, regex, linq);
- Stopwatch si = newStopwatch();
- Stopwatch sd = newStopwatch();
- Stopwatch sl = newStopwatch();
- Stopwatch ss = newStopwatch();
- si.Start();
- for(inti = 0;i <100;i++)
- {
- index = LinesCountIndexOf(s);
- }
- si.Stop();
- ss.Start();
- for(inti = 0;i <100;i++)
- {
- index = LinesCountSplit(s);
- }
- ss.Stop();
- sd.Start();
- for(inti = 0;i <100;i++)
- {
- index = LinesCountRegex(s);
- }
- sd.Stop();
- sl.Start();
- for(inti = 0;i <100;i++)
- {
- index = LinesCountLinq(s);
- }
- sl.Stop();
輸入的文件是1.64Mb,包含大約23K行。
測試結果顯示是
22777:22777:22777
有意思的是這個執行時間的結果(ms計)
Test ElapsedMilliseconds
BF+I 181
Split 1089
Regex 2557
Linq 3590
我本來想著這正則要快的不是一點點啊。正則和Linq這么大的差異令我震驚了,最令我震驚的是BF+I竟然比他們兩個都快,而分割則毫無疑問比Index要慢,因為在分割方法中.net一次要分配23k的字符串空間
為了完成任務,我把BF+I版本重寫了一個類,并且判斷了字符串只有一行的情況,如你期望的一樣,不要一秒就完成了
- staticclassExtensionMethods
- {
- ///<summary>
- ///Returns the number of lines in a string///</summary>
- ///<param name="s"></param>
- ///<returns></returns>
- publicstaticlongLines(thisstrings)
- {
- longcount = 1;
- intposition = 0;
- while((position = s.IndexOf(' ', position)) != -1)
- {
- count++;
- position++; //Skip this occurance!
- }
- returncount;
- }
- }
注:count初始為1后,時間更短了一些。
Test ElapsedMilliseconds
BF+I 170
Split 1089
Regex 2063
Linq 3583
完成。。
原文鏈接:http://www.cnblogs.com/lazycoding/archive/2012/01/09/2317552.html
【編輯推薦】