它是更有效的比较整数和整数或字符串和字符串 [英] Is it more efficient to compare ints and ints or strings and strings
问题描述
我有C#编写的,其中也有不少整数和字符串之间进行比较的程序。
I've got a program written in c# where there are a lot of comparisons between ints and strings.
因此,对于性能的原因,我只是想知道哪些?更有效
So for performance reasons I would just like to know which is more efficient?
如果我们有:
int a = 5;
string b = "5";
if(a == int.Parse(b))
{
}
OR
if(a.ToString() == b)
{
}
推荐答案
几点意见提到运行的分析工具来证明它具有更好的性能。
A few comments mentioned running a profiling tool to prove which has better performance.
这是一个好的,但检查特定语句的性能是把它们放在一个循环,并用秒表类最简单的方法。
This is a ok, but the simplest way to check performance of specific statements is to put them in a loop and use the Stopwatch class.
杰夫阿特伍德问起这使这类时机,即使在的这个问题。在这个问题和答案,你也可以找到一些不错的代码示例和背景细节
Jeff Atwood asked about making this sort of timing even simpler in this question. In that question and answer you will also find some good code examples and background details.
继承人一个非常简单的例子:
Heres a very simple working example:
System.Diagnostics.Stopwatch sw=new System.Diagnostics.Stopwatch();
int a = 5;
string b = "5";
sw.Start();
for (int i=0;i<1000000;i++)
{
if(a == int.Parse(b))
{
}
}
sw.Stop();
Console.WriteLine("a == int.Parse(b) milliseconds: " + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
for (int i=0;i<1000000;i++)
{
if(a.ToString() == b)
{
}
}
sw.Stop();
Console.WriteLine("a.ToString() == b milliseconds: " + sw.ElapsedMilliseconds);
在我的电脑输出:
一个== int.Parse(二)毫秒:521
a == int.Parse(b) milliseconds: 521
a.ToString()== b毫秒:697
a.ToString() == b milliseconds: 697
因此,在这种简单的场景int.Parse()是速度稍快,但还不足以真正担心的。
So in this simple scenario int.Parse() is slightly faster, but not enough to really worry about.
这篇关于它是更有效的比较整数和整数或字符串和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!