Convert.ChangeType和Convert.ToInt32有什么主要区别?

7

在Convert.ChangeType、Convert.ToInt32和int.Parse之间,有没有性能上的优势?


1
不要忘记 Int32.TryParse(String, out int),它提供了一些不错的可能性。 - basti
4个回答

9
如果您知道将一个字符串转换为Int32,使用Convert.ChangeType似乎是一种晦涩的方法。我肯定更喜欢其他两个方法中的任何一个。
int.Parse和Convert.ToInt32(x)之间的主要区别在于Convert.ToInt32(null)返回0,而int.Parse(null)会抛出异常。当然,int.Parse还可以让您更好地控制使用哪种文化。
我非常怀疑其中一个方法比另一个方法更具有性能优势:我期望Convert.ToInt32调用int.Parse而不是反过来,但它没有被记录下来。单个方法调用的影响不太可能显著(它可能已经被内联了)。

Convert.ToInt32()和Int32.Parse()都使用(不公开)的方法System.Number.ParseInt32(),该方法又调用System.Number.StringToNumber()。我怎么知道的?看看传递无效字符串时生成的FormatException的堆栈跟踪即可 :-) - Elian Ebbing
@user532870:说得也没错,但我仍然不会依赖那种东西 :) - Jon Skeet
@user532870:Jon是对的。反射显示Convert.ToInt32调用int.Parse,而int.Parse又调用Number.ParseInt32。 @Jon:那么int.Parse更好吗? - naveen
1
@naveen:这取决于您想要的确切行为。如果您满意使用当前文化并希望它返回0以表示null,则使用Convert.ToInt32。如果您想要int.Parse的行为,请使用它 :) - Jon Skeet

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);
    }

这个简单的测试结果如下:

266 on CalcChangeTypePerf
167 on CalcToInt32Perf
165 on CalcIntParse

2
你在每个测试中都创建了一百万个对象,这是不必要的。虽然每个测试在这方面上都是“相等”的,但这意味着实际解析时间的相对差异会被掩盖,而且可能会有垃圾回收在一个测试中清理另一个测试的垃圾。我建议你在开始时创建一个字符串数组,并重复使用它。 - Jon Skeet

0

简单测试显示Parse()是最快的方法,其次是Convert.ToInt32(),最后是Convert.ChangeType()

static void Main(string[] args)
{
    string s = "104563";
    int a = 1;

    for (int k = 0; k < 4; k++)
    {
        Stopwatch w = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
            a = (int)Convert.ChangeType(s, typeof(int));
        w.Stop();

        Console.WriteLine("ChangeType={0}", w.ElapsedMilliseconds);

        Stopwatch w1 = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
            a = Convert.ToInt32(s);
        w1.Stop();

        Console.WriteLine("ToInt32={0}", w1.ElapsedMilliseconds);

        Stopwatch w2 = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
            a = Int32.Parse(s);
        w2.Stop();
        Console.WriteLine("Parse={0}", w2.ElapsedMilliseconds);
    }

    Console.ReadLine();
}

结果是:

ChangeType=2422
ToInt32=1859
Parse=1760
ChangeType=2374
ToInt32=1857
Parse=1762
ChangeType=2378
ToInt32=1860
Parse=1763
ChangeType=2375
ToInt32=1855
Parse=1759

0

是的。

在相同的目的下,Convert.ToInt32比使用Convert.ChangeType更好。

ChangeType是一个通用的转换方法,将由value指定的对象转换为conversionType。而ToInt32则专门用于int32类型。


1
实际上,ChangeType() 是编程中的 cast,而 Convert.ToInt32() 真正从其他类型创建 int - abatishchev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接