【发布时间】:2025-12-28 11:15:06
【问题描述】:
在开发我的应用程序时,我遇到了一些比较的东西:
string str = "12345";
int j = 12345;
if (str == j.ToString())
{
//do my logic
}
我在想上面的东西也可以用:
string str = "12345";
int j = 12345;
if (Convert.ToInt32(str) == j)
{
//do my logic
}
所以我开发了一个示例代码来测试哪个更好
var iterationCount = 1000000;
var watch = new Stopwatch();
watch.Start();
string str = "12345";
int j = 12345;
for (var i = 0; i < iterationCount; i++)
{
if (str == j.ToString())
{
//do my logic
}
}
watch.Stop();
第二个:
var iterationCount = 1000000;
var watch = new Stopwatch();
watch.Start();
string str = "12345";
int j = 12345;
for (var i = 0; i < iterationCount; i++)
{
if (Convert.ToInt32(str) == j)
{
//do my logic
}
}
watch.Stop();
在运行上述两个测试时,我发现上述测试所用的时间几乎相同。我想讨论哪个是更好的方法?有没有比两个以上两个更好的方法?
【问题讨论】:
标签: c# comparison