我有一个用c#编写的程序,其中有一些int和字符串之间的比较.
因此,出于性能原因,我想知道哪个更有效?
如果我们有:
int a = 5;
string b = "5";
if(a == int.Parse(b)) { }
Run Code Online (Sandbox Code Playgroud)
要么
if(a.ToString() == b) { }
Run Code Online (Sandbox Code Playgroud)
我实际上使用一些示例和定时循环来描述它.事实证明,小整数的Parse胜利,而大型的ToString胜利.这种差异是如此之小,不应该成为一个问题,正如其他人所提到的那样,通过考虑字符串根本不代表整数的情况,你可能会做出更好的选择.
编辑:对于那些感兴趣的人,这里是来源,快速'n'脏:
using System;
using System.Diagnostics;
namespace CompareTest
{
static class Program
{
static void Main(string[] args)
{
int iterations = 10000000;
int a = 5;
string b = "5";
Stopwatch toStringStopwatch = new Stopwatch();
toStringStopwatch.Start();
for (int i = 0; i < iterations; i++) {
bool dummyState = a.ToString() == b;
}
toStringStopwatch.Stop();
Stopwatch parseStopwatch = new Stopwatch();
parseStopwatch.Start();
for (int i = 0; i < iterations; i++) {
bool dummyState = a == int.Parse(b);
}
parseStopwatch.Stop();
Console.WriteLine("ToString(): {0}", toStringStopwatch.Elapsed);
Console.WriteLine("Parse(): {0}", parseStopwatch.Elapsed);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
一些评论提到运行分析工具来证明哪个具有更好的性能.
这是好的,但检查特定语句性能的最简单方法是将它们放在循环中并使用Stopwatch类.
杰夫阿特伍德询问在这个问题中使这种时间更简单.在那个问题和答案中,您还会找到一些很好的代码示例和背景细节.
下面是一个非常简单的工作示例:
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);
Run Code Online (Sandbox Code Playgroud)
在我的电脑上输出:
a == int.Parse(b)毫秒:521
a.ToString()== b毫秒:697
所以在这个简单的场景中,int.Parse()稍快一点,但还不够真正担心.
| 归档时间: |
|
| 查看次数: |
7335 次 |
| 最近记录: |