c# - 比较ints和ints还是比较strings和strings效率更高

标签 c# performance

我有一个用 c# 编写的程序,其中有很多整数和字符串之间的比较。

所以出于性能原因,我只想知道哪个效率更高?

如果我们有:

int a  = 5;
string b = "5";

if(a == int.Parse(b)) { }

if(a.ToString() == b) { }

最佳答案

我实际上使用一些示例和定时循环对此进行了分析。事实证明,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();
        }
    }
}

关于c# - 比较ints和ints还是比较strings和strings效率更高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1642659/

相关文章:

c# - 如何在不安装SQL Server的情况下在Visual Studio C#项目中获取SQL?

performance - 客户端缓存有问题吗?

html - 多设备设计速度问题

c# - C#套接字阻止行为

c# - 我可以减少 WPF 应用程序中手写笔/触摸输入的开销吗?

python - 集合中的快速随机元素 - Python

python - 高效读取文件中的某一行

c# - 如何在 Unity - Android 中以这种共享 Intent 的方式强制选择器?

c# - Linq 对象 : inner query performance

c# - ASP :dropdownlist width: How to make the control narrower than the dropdown list