刚才看到一篇关于字符串反转的文章,原文地址
http://www.cnblogs.com/Mars_Chen/archive/2010/03/04/1678123.html
当时第一感觉是用Array类的reverse方法多好,何必用正则这么麻烦呢?要知道正则虽然看起来简单,但是真正匹配起来可也不容易,于是便一时好奇把这两种方法比较了一下,谁知不比不知道,一比吓一跳啊。下面看代码和结果
{
Stopwatch sw = new Stopwatch();
Stopwatch swavg = new Stopwatch();
swavg.Start();
for ( int j = 0 ; j < 10 ; j ++ )
{
sw.Start();
for ( int i = 0 ; i < 100000 ; i ++ )
{
Reverse1( " Who will be faster? Yours or mine? Do you really mind my test? " );
}
sw.Stop();
Console.WriteLine( " My Method --- Each time: " + sw.Elapsed.ToString());
sw.Reset();
}
swavg.Stop();
Console.WriteLine( " My Method --- Avg time: " + (sw.ElapsedMilliseconds / 10 ).ToString());
swavg.Reset();
swavg.Start();
for ( int j = 0 ; j < 10 ; j ++ )
{
sw.Start();
for ( int i = 0 ; i < 100000 ; i ++ )
{
Reverse2( " Who will be faster? Yours or mine? Do you really mind my test? " );
}
sw.Stop();
Console.WriteLine( " Your Method --- Each time: " + sw.Elapsed.ToString());
sw.Reset();
}
swavg.Stop();
Console.WriteLine( " Your Method --- Avg time: " + (sw.ElapsedMilliseconds / 10 ).ToString());
Console.ReadLine();
}
static string Reverse1( string original)
{
char [] arr = original.ToCharArray();
Array.Reverse(arr);
return new string (arr);
}
static string Reverse2( string original)
{
string result = "" ;
MatchCollection mc = Regex.Matches(original, @" (\S)+ " );
for ( int i = mc.Count - 1 ; i >= 0 ; i -- )
{
result += mc[i].Value;
}
return result;
}
执行结果
My Method --- Each time:00:00:00.0304430
My Method --- Each time:00:00:00.0258621
My Method --- Each time:00:00:00.0243496
My Method --- Each time:00:00:00.0272635
My Method --- Each time:00:00:00.0394696
My Method --- Each time:00:00:00.0242083
My Method --- Each time:00:00:00.0291635
My Method --- Each time:00:00:00.0289069
My Method --- Each time:00:00:00.0243922
My Method --- Each time:00:00:00.0263951
My Method --- Avg time:28
Your Method --- Each time:00:00:01.6769779
Your Method --- Each time:00:00:01.6586320
Your Method --- Each time:00:00:01.6922838
Your Method --- Each time:00:00:01.6572740
Your Method --- Each time:00:00:01.6599065
Your Method --- Each time:00:00:01.6630039
Your Method --- Each time:00:00:01.7182288
Your Method --- Each time:00:00:01.9108913
Your Method --- Each time:00:00:01.7913726
Your Method --- Each time:00:00:01.7917344
Your Method --- Avg time:1722