Convert.ChangeType或Convert.ToInt32之间的主要区别是什么?

Pri*_*aka 6 c#

在Convert.ChangeType或Convert.ToInt32或int.Parse中,是否有任何性能优势

Jon*_*eet 8

如果你知道你将要转换stringInt32,使用这Convert.ChangeType似乎是一种不明智的方式.我肯定更喜欢其他任何一个电话.

int.Parse和之间的主要区别Convert.ToInt32(x)Convert.ToInt32(null)返回0,其中as int.Parse(null)将抛出异常.当然,int.Parse还可以让您更好地控制使用何种文化.

我非常怀疑一个在另一个上面有任何性能优势:我希望 Convert.ToInt32调用int.Parse而不是反过来 - 但是没有记录以这种方式工作,并且单个方法调用的命中不太可能是重要的.(无论如何,它可能会被内联.)


Ars*_*yan 5

private const int maxValue = 1000000;
    static void Main(string[] args)
    {
        string[] strArray = new string[maxValue];
        for (int i = 0; i < maxValue; i++)
        {
            strArray[i] = i.ToString();
        }
        int[] parsedNums = new int[maxValue];
        CalcChangeTypePerf(strArray,parsedNums);
        CalcToInt32Perf(strArray, parsedNums);
        CalcIntParse(strArray, parsedNums);
    }
    public static void CalcChangeTypePerf(string[] strArray,int[] parsedArray)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for (int i = 0; i < maxValue; i++)
        {
            parsedArray[i] = (int)Convert.ChangeType(strArray[i], typeof(int));
        }
        stopwatch.Stop();
        Console.WriteLine("{0} on CalcChangeTypePerf", stopwatch.ElapsedMilliseconds);
    }
    public static void CalcToInt32Perf(string[] strArray, int[] parsedArray)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for (int i = 0; i < maxValue; i++)
        {
            parsedArray[i] = Convert.ToInt32(strArray[i]);
        }
        stopwatch.Stop();
        Console.WriteLine("{0} on CalcToInt32Perf", stopwatch.ElapsedMilliseconds);
    }
    public static void CalcIntParse(string[] strArray, int[] parsedArray)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for (int i = 0; i < maxValue; i++)
        {
            parsedArray[i] = int.Parse(strArray[i]);
        }
        stopwatch.Stop();
        Console.WriteLine("{0} on CalcIntParse", stopwatch.ElapsedMilliseconds);
    }
Run Code Online (Sandbox Code Playgroud)

这个简单的测试结果

266 on CalcChangeTypePerf
167 on CalcToInt32Perf
165 on CalcIntParse
Run Code Online (Sandbox Code Playgroud)

  • 您不必要地在每个测试中创建一百万个对象。尽管每个测试都以这种方式“相等”,但这意味着实际的“解析”时间的相对差异被某种程度的掩盖了,并且一个测试中可能存在垃圾收集,而从另一个测试中清除了垃圾。我建议您从头开始创建一个字符串数组*一次并重用它。 (2认同)