开发者

Which is better to use: Convert.ToX or X.Parse(...)?

I'm using reflection to create some objects. The values I'm setting are read in from a file so they're natively in a string format and I need to convert them to the datatype of the property.

My question is, which is f开发者_高级运维aster/better to use: the Convert.ToX(...) methods or the X.Parse(...) methods?


All of the Convert.ToX functions that accept an argument of type string ultimately call down to the Parse method of the appropriate datatype anyway.

For example, Convert.ToInt32(string) looks something like this:

public static int ToInt32(string value)
{
   if (value == null)
   {
      return 0;
   }
   return int.Parse(value, CultureInfo.CurrentCulture);
}

The same thing for all of the other numeric conversion methods, including Decimal and DateTime. So it's fairly irrelevant which one you use; the result (and speed) will be the same in either case.

Really, the only difference is the if (value == null) guard clause at the beginning. Whether or not that's convenient depends on the specific use case. Generally, if you know that you have a non-null string object, you might as well use Parse. If you're not sure, ConvertToX is a safer bet, requring less null-checking code inline.


They are exactly the same! The Convert.ToX(String) methods actually call the X.Parse(String) methods.


Another possibility is the TryParse methods. These are particularly useful if there is a possibility that the value cannot be parsed successfully. Instead of throwing an exception the call will return a bool indicating whether the operation was successful. This executes much faster and is a cleaner implementation as compared to dealing with the exception.


According to what i see in Reflector , Convert form string is a wrapper around Parse. so it stand to reason using parse is marginally better in performance.

EDIT: after Cody pointed out that optimization will make the difference almost nothing, i tested on my machine, and indeed the execution times for Parse and Convert came out the same when parsing 1 million inetgers in a loop.

EDIT2: here you go yas4891 ,its actually the code you used with very minor changes.

public static void Main()
        {
            int tRuns = 1000000;
            List<String> tList = new List<string>();
            for (int i = 0; i < tRuns; i++) tList.Add(i.ToString());
            Stopwatch s = new Stopwatch();
            s.Start();
            int tSum = 0;
            for (int i = tRuns - 1; i >= 0; i--) 
            {
                tSum += Convert.ToInt32(tList[i]);
            }
            s.Stop();
            Console.WriteLine("convert: " + s.ElapsedMilliseconds);

            Console.WriteLine("tSum:" + tSum); 

            s.Reset();
            s.Start();
            tSum = 0; 
            for (int i = tRuns - 1; i >= 0; i--) 
            { 
                tSum += Int32.Parse(tList[i]); 
            } 
            s.Stop();
            Console.WriteLine("parse: " + s.ElapsedMilliseconds);
            Console.WriteLine("tSum:" + tSum);
            Console.ReadKey();
        }


using the following code

int tRuns = 1000000;
List<String> tList = new List<string>();

for (int i = 0; i < tRuns; i++)
   tList.Add(i.ToString());


PerformanceMeter.Start();
int tSum = 0;
for (int i = tRuns-1; i >= 0; i--)
{
   tSum += Convert.ToInt32(tList[i]);
}

PerformanceMeter.LogAndStop("using Convert.ToInt32:");

cLogger.Info("tSum:" + tSum);
PerformanceMeter.Start();

tSum = 0;
for (int i = tRuns-1; i >= 0; i--)
{
   tSum += Int32.Parse(tList[i]);
}

PerformanceMeter.LogAndStop("using Int32.Parse:");
cLogger.Info("tSum:" + tSum);

gives me the following output:

{ PerformanceMeter}:178 INFO: - using Convert.ToInt32:: 233,0133 ms
{ Program}: 92 INFO: - tSum:1783293664
{ PerformanceMeter}:178 INFO: - using Int32.Parse:: 179,0103 ms
{ Program}:102 INFO: - tSum:1783293664

So at least for Int32 it seems to be more efficient to use Int32.Parse. However this may be different in your scenario and I suppose you should do a similiar test.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜