tryParse, try/catch(Parse), Convert比较

只是一个别人写的文章精简一下,原文在这里:http://blogs.msdn.com/ianhu/archive/2005/12/19/505702.aspx

话不多,直接上代码:

 

ExpandedBlockStart.gif 代码
private  List < Int32 >  TestParse(String[] strings)

{

Int32 intValue;

List
< Int32 >  intList  =   new  List < int > ();

 

for  ( int  i  =   0 ; i  <   5000000 ; i ++ )

{

intList.Clear();

 

foreach  (String str  in  strings)

{

try

{

intValue 
=  Int32.Parse(str);

intList.Add(intValue);

}

 

catch  (System.ArgumentException)

                     { }

 

                     
catch  (System.FormatException)

                     { }

 

                     
catch  (System.OverflowException)

             { }

}

 

}

 

return  intList;

}

 

private  List < Int32 >  TestTryParse(String[] strings)

{

Int32 intValue;

List
< Int32 >  intList  =   new  List < int > ();

Boolean ret;

 

for  ( int  i  =   0 ; i  <   5000000 ; i ++ )

{

intList.Clear();

 

foreach  (String str  in  strings)

                     {

                           ret 
=  Int32.TryParse(str,  out  intValue);

                     
if  (ret)

                     {

                                  intList.Add(intValue);

                     }

             }

       }

 

       
return  intList;

}

 

private  List < Int32 >  TestConvert(String[] strings)

{

Int32 intValue;

List
< Int32 >  intList  =   new  List < int > ();

 

for  ( int  i  =   0 ; i  <   5000000 ; i ++ )

{

intList.Clear();

 

foreach  (String str  in  strings)

{

try

{

intValue 
=  Convert.ToInt32(str);

intList.Add(intValue);

}

 

catch  (System.FormatException)

{ }

 

catch  (System.OverflowException)

{ }

}

}

 

return  intList;

}

 

测试正确数据:

{ "123", "4567", "7890", "1", "1231280", "10" }.

 

三者性能差不多。

 

测试错误数据:

{ "12345", null, "123", "1324dfs", "51235", String.Empty, "43", "4123412341234123412341234123412341234123" }.

 

如图所见:tryParse>Convert>Parse

原因在于Convert跟Parse要进行异常处理,尤其是Parse的ArgumentNullException处理开销很大。

 

总结:

在没特殊需求的情况下强烈建议使用tryParse

转载于:https://www.cnblogs.com/kiracn/archive/2010/01/31/1660441.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值