哪个更好用:Convert.ToX 或 X.Parse(...)?

发布于 2024-11-06 23:35:36 字数 155 浏览 0 评论 0原文

我正在使用反射来创建一些对象。我设置的值是从文件中读取的,因此它们本身就是字符串格式,我需要将它们转换为属性的数据类型。

我的问题是,使用 Convert.ToX(...) 方法或 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 faster/better to use: the Convert.ToX(...) methods or the X.Parse(...) methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

迟月 2024-11-13 23:35:36

无论如何,所有接受 string 类型参数的 Convert.ToX 函数最终都会调用相应数据类型的 Parse 方法。

例如,Convert.ToInt32(string) 看起来像这样:

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

对于所有其他数字转换方法(包括 DecimalDateTime)都是一样的。因此,您使用哪一个是相当无关紧要的;在任何一种情况下,结果(和速度)都是相同的。

实际上,唯一的区别是开头的 if (value == null) 保护子句。这是否方便取决于具体的用例。一般来说,如果你知道你有一个非空的string对象,你不妨使用Parse。如果您不确定,ConvertToX 是一个更安全的选择,需要更少的内联空检查代码。

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.

梦回梦里 2024-11-13 23:35:36

他们是一模一样的! Convert.ToX(String) 方法实际上调用 X.Parse(String) 方法。

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

荒芜了季节 2024-11-13 23:35:36

另一种可能性是 TryParse 方法。如果存在无法成功解析该值的可能性,这些尤其有用。该调用不会抛出异常,而是返回一个 bool 指示操作是否成功。与处理异常相比,这执行得更快并且是更干净的实现。

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.

绳情 2024-11-13 23:35:36

根据我在 Reflector 中看到的,Convert 表单字符串是 Parse 的包装器。所以按理说使用 parse 的性能会稍微好一些。

编辑:在科迪指出优化几乎不会产生任何差异之后,我在我的机器上进行了测试,事实上,解析时 ParseConvert 的执行时间是相同的100 万个 inetgers 循环。

编辑2:这里是yas4891,它实际上是您使用的代码,进行了非常小的更改。

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();
        }

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();
        }
热鲨 2024-11-13 23:35:36

使用以下代码

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);

给出以下输出:

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

所以至少对于 Int32 来说,使用 Int32.Parse 似乎更有效。然而,这在你的场景中可能会有所不同,我想你应该做一个类似的测试。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文