刚才看到一个关于字符串反转的例子

刚才看到一篇关于字符串反转的文章,原文地址

http://www.cnblogs.com/Mars_Chen/archive/2010/03/04/1678123.html

当时第一感觉是用Array类的reverse方法多好,何必用正则这么麻烦呢?要知道正则虽然看起来简单,但是真正匹配起来可也不容易,于是便一时好奇把这两种方法比较了一下,谁知不比不知道,一比吓一跳啊。下面看代码和结果

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
static void Main( string [] args)
{
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

转载于:https://www.cnblogs.com/babybear/archive/2010/03/04/1678515.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值