What is fastest: (int), Convert.ToInt32(x) or Int32.Parse(x)?

后端 未结 15 1159
南笙
南笙 2021-02-02 06:13

Which of the following code is fastest/best practice for converting some object x?

int myInt = (int)x;

or

int myInt = Convert.T         


        
相关标签:
15条回答
  • 2021-02-02 06:39

    Best practice would be TryParse, and seeing the result of that, if it worked - otherwise you could get exceptions

    0 讨论(0)
  • 2021-02-02 06:41

    If you had the need for the extra speed, it would be easy to test the different the different options. Since you aren't testing them, you mustn't need them. Don't waste your time with pointless micro-optimizations!

    0 讨论(0)
  • 2021-02-02 06:46

    If you know that the data is definitely int then int myInt = (int)x; should be the fastest option. Otherwise TryParse will help you to get it right without the slowness of exceptions.

    BTW :

    (int) only unboxes therefore faster,

    (int) IL =

      .locals init (
            [0] object x,
            [1] int32 Y)
        L_0000: ldc.i4.1 
        L_0001: box int32
        L_0006: stloc.0 
        L_0007: ldloc.0 
        L_0008: unbox int32
        L_000d: ldobj int32
        L_0012: stloc.1 
        L_0013: ret 
    

    Convert.Toint32=

    .locals init (
            [0] object x,
            [1] int32 Y)
        L_0000: ldc.i4.1 
        L_0001: box int32
        L_0006: stloc.0 
        L_0007: ldloc.0 
        L_0008: call object [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::GetObjectValue(object)
        L_000d: call int32 [mscorlib]System.Convert::ToInt32(object)
        L_0012: stloc.1 
        L_0013: ret 
    
    0 讨论(0)
  • 2021-02-02 06:48

    Why don't you just try it a couple of thousand times?

    (this goes for all "What is fastest:" questions)


    Hmmm, lots of downvotes over the years... I guess I should expand on this answer.

    The above statement was made with a degree of flippancy in my youth, however I still agree with its sentiment. It is not worthwhile spending time creating a SO question asking others what they think is faster out of two or three operations that take less than 1ms each.

    The fact that one might take a cycle or two longer than the other will almost certainly be negligible in day-to-day usage. And if you ever notice a performance problem in your application when you are converting millions of objects to ints, that's the point where you can profile the actual code, and you'll easily be able to test whether the int conversion is actually the bottleneck.

    And whereas today it's the object-int converter, tomorrow maybe you'll think your object-DateTime converter is taking a long time. Would you create another SO question to find out what's the fastest method?

    As for your situation (no doubt long since resolved by now), as mentioned in a comment, you are querying a database, so object-int conversion is the least of your worries. If I was you I would use any of the conversion methods you mentioned. If a problem arises I would isolate the call, using a profiler or logging. Then when I notice that object-int conversion is being done a million times and the total time taken by that conversion seems relatively high, I would change to using a different conversion method and re-profile. Pick the conversion method that takes the least time. You could even test this in a separate solution, or even LINQPad, or Powershell etc.

    0 讨论(0)
  • 2021-02-02 06:49

    When I have questions about performance differences between different ways of doing something specific like this, I usually make a new entry in my copy of MeasureIt, a free download from a great MSDN article from Vance Morrison. For more information please refer to the article.

    By adding a simple bit of code to MeasureIt, I get the results below which compare the actual timings of the various methods of converting to int. Note the cast from string to int will throw an exception and isn't valid, so I just added the permutations that made sense to me.

     
    Name                                                Median   Mean     StdDev   Min      Max    Samples       
    IntCasts: Copy [count=1000 scale=10.0]              0.054    0.060    0.014    0.054    0.101    10       
    IntCasts: Cast Int [count=1000 scale=10.0]          0.059    0.060    0.007    0.054    0.080    10       
    IntCasts: Cast Object [count=1000 scale=10.0]       0.097    0.100    0.008    0.097    0.122    10       
    IntCasts: int.Parse [count=1000 scale=10.0]         2.721    3.169    0.850    2.687    5.473    10       
    IntCasts: Convert.ToInt32 [count=1000 scale=10.0]   3.221    3.258    0.067    3.219    3.418    10     
    


    To find the best performance for the various types you are interested in, just extend the code below, which is literally all I had to add to MeasureIt to generate the above table.

    static unsafe public void MeasureIntCasts()
    {
        int result;
        int intInput = 1234;
        object objInput = 1234;
        string strInput = "1234";
    
        timer1000.Measure("Copy", 10, delegate
        {
            result = intInput;
        });
        timer1000.Measure("Cast Object", 10, delegate
        {
            result = (int)objInput;
        });
    
        timer1000.Measure("int.Parse", 10, delegate
        {
            result = int.Parse(strInput);
        });
    
        timer1000.Measure("Convert.ToInt32", 10, delegate
        {
            result = Convert.ToInt32(strInput);
        });
    }
    
    0 讨论(0)
  • 2021-02-02 06:50

    Someone's already done the benchmarking. Here are the results. The fastest way if you know what you're converting will always be a valid int, is to use the following method (which a few people have answered above) :

    int value = 0;
    for (int i = 0; i < str.Length; i++)
    {
        value = value * 10 + (str[i] - '0');
    }
    

    Other techniques that were benchmarked were:

    • Convert.ToInt32
    • Int32.TryParse
    • int.Parse
    0 讨论(0)
提交回复
热议问题