将int转换为字符串或将字符串转换为int之间的性能差异

时间:2013-11-19 19:45:29

标签: c# .net

我在字符串和整数之间做了很多比较,并且想知道这两者中哪一个提供了更好的性能。

这一个:

int a = 1;
string b = "1";
bool isEqual = a == int.Parse(b);

或者这个:

int a = 1;
string b = "1";
bool isEqual = a.ToString() == b;

编辑:在Elliott Frisch的评论之后,我将下面的代码编写为基准测试,我从中得到了这些:https://stackoverflow.com/a/15108875/629211。接受的答案也有效。

int a = 1;
string b = "1";

Stopwatch watch1 = new Stopwatch();
watch1.Start();

for (int i = 1; i < 1000000; i++)
{
    bool isEqual = a == int.Parse(b);
}

watch1.Stop();

Stopwatch watch2 = new Stopwatch();
watch2.Start();

for (int i = 1; i < 1000000; i++)
{
    bool isEqual = a.ToString() == b;
}

watch2.Stop();

Console.WriteLine("Option 1: {0} ms", watch1.Elapsed);
Console.WriteLine("Option 2: {0} ms", watch2.Elapsed);

BTW答案是第二种选择。

1 个答案:

答案 0 :(得分:3)

几分钟的工作,您可以合理地自己对此进行基准测试,以发现差异。

1.)创建通用计时例程。

  public void RunTest(Action action, String name, Int32 iterations)
  {
      var sw = new System.Diagnostics.Stopwatch();
      System.GC.Collect();
      System.GC.WaitForPendingFinalizers();

      sw.Start();

      for(var i = 0; i<iterations; i++)
      {
          action();
      }

      sw.Stop();

      Console.Write("Name: {0},", name);
      Console.Write(" Iterations: {1},", iterations);
      Console.WriteLine(" Milliseconds: {2}", sw.ElapsedMilliseconds);
  }

2.。)创建两个测试函数。

  public void CompareWithParseInt()
  {
      int a = 1;
      string b = "1";
      bool isEqual = a == int.Parse(b);
  }
  public void CompareWithToString()
  {
      int a = 1;
      string b = "1";
      bool isEqual = a.ToString() == b;
  }

3。)现在对它们进行基准测试。

RunTest(CompareWithParseInt, "Compare With ParseInt", 1);
//Name: Compare With ParseInt, Iterations: 1, Milliseconds: 0
RunTest(CompareWithParseInt, "Compare With ParseInt", 1);
//Name: Compare With ParseInt, Iterations: 1, Milliseconds: 0
RunTest(CompareWithParseInt, "Compare With ParseInt", 10);
//Name: Compare With ParseInt, Iterations: 10, Milliseconds: 0
RunTest(CompareWithParseInt, "Compare With ParseInt", 100);
//Name: Compare With ParseInt, Iterations: 100, Milliseconds: 0
RunTest(CompareWithParseInt, "Compare With ParseInt", 1000);
//Name: Compare With ParseInt, Iterations: 1000, Milliseconds: 0
RunTest(CompareWithParseInt, "Compare With ParseInt", 100000);
//Name: Compare With ParseInt, Iterations: 100000, Milliseconds: 12
RunTest(CompareWithParseInt, "Compare With ParseInt", 1000000);
//Name: Compare With ParseInt, Iterations: 1000000, Milliseconds: 133
RunTest(CompareWithToString, "Compare With ToString", 1000000);
//Name: Compare With ToString, Iterations: 1000000, Milliseconds: 112
RunTest(CompareWithToString, "Compare With ToString", 100000000);
//Name: Compare With ToString, Iterations: 100000000, Milliseconds: 10116
RunTest(CompareWithParseInt, "Compare With ParseInt", 100000000);
//Name: Compare With ParseInt, Iterations: 100000000, Milliseconds: 12447

<强>结论:

正如您在这种特殊情况下所看到的,如果您的应用程序存在瓶颈,您几乎可以做任何让您满意的事情。它不是上面的代码:)