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

后端 未结 15 1157
南笙
南笙 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:27

    this is not true. The fast conversion is direct cast:

    int i = (int) stringData;
    
    watch.Elapsed = {00:00:00.1732388}
    watch2.Elapsed= {00:00:00.0878196}
    
    
     // Mesary start
                    Stopwatch watch = new Stopwatch();
    
                    watch.Start();
                    for (int f = 1; f < 1000000; f++)
                    {
                        item.Count = FastInt32.IntParseFast(dt.Rows[i]["TopCount"]);
                    }   // Execute the task to be timed
                    watch.Stop();
    
                    Console.WriteLine("Elapsed: {0}", watch.Elapsed);
                    Console.WriteLine("In milliseconds: {0}", watch.ElapsedMilliseconds);
                    Console.WriteLine("In timer ticks: {0}", watch.ElapsedTicks);
                    // Mesary end
    
    
                    // Mesary start
                    Stopwatch watch2 = new Stopwatch();
    
                    watch2.Start();
                    for (int n = 1; n < 1000000; n++)
                    {
                        item.Count = (int)(dt.Rows[i]["TopCount"]);
                    }   // Execute the task to be timed
                    watch2.Stop();
    
                    Console.WriteLine("Elapsed: {0}", watch2.Elapsed);
                    Console.WriteLine("In milliseconds: {0}", watch2.ElapsedMilliseconds);
                    Console.WriteLine("In timer ticks: {0}", watch2.ElapsedTicks);
                    // Mesary end
    
    0 讨论(0)
  • 2021-02-02 06:29

    In the end, they all end up calling:

    System.Number.ParseInt32(string s, NumberStyles style, NumberFormatInfo info);
    

    So in summary, there will be no difference what so ever.

    Have a look in .Net Reflector to see this.

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

    Extending the test of Eric Cosky by alternatives from Sam Allen, i found that if you know that your string is a valid integer, then parsing it by yourself is much faster.

    I extended the test by the following cases:

        timer1000.Measure("IntParseFast", 10, delegate
        {
            result = Misc.IntParseFast(strInput);
        });
    
        timer1000.Measure("IntParseUnsafe", 10, delegate
        {
            result = Misc.IntParseUnsafe(strInput);
        });
    

    With the following implementations:

    public static int IntParseFast(string value)
    {
        int result = 0;
        int length = value.Length;
        for (int i = 0; i < length; i++)
        {
            result = 10 * result + (value[i] - 48);
        }
        return result;
    }
    
    public unsafe static int IntParseUnsafe(string value)
    {
        int result = 0;
        fixed (char* v = value)
        {
            char* str = v;
            while (*str != '\0')
            {
                result = 10 * result + (*str - 48);
                str++;
            }
        }
        return result;
    }
    

    I get the following results:

    IntCaint.Parse                5,495
    IntCaConvert.ToInt32          5,653
    IntCaIntParseFast             1,154
    IntCaIntParseUnsafe           1,245
    
    0 讨论(0)
  • 2021-02-02 06:38
    foreach(DataRow row in someTable.Rows)
    {
        myInt = (int)row["some int value"];
        myInt2 = Int.Parse(row["some int value"]);
        myInt2 = Convert.ToInt32(row["some int value"]);
    }
    

    For this example, if the value coming from the table is indeed an int value, or comparable database value, then using the

    myInt = (int)row["some int value"];
    

    would be the most efficient, and hence the 'fastest' becuase the

    row["some int value"];
    

    will be a value-type int instance boxed inside an reference-type object instance, so using the explicit type cast will be the quickest becuase as other people said it is an operation not a function call, thereby reducing the cpu operations required. A call to a converion or parse method would require extra cpu operations and hence not be as 'fast'.

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

    It depends on what you expect x to be

    If x is a boxed int then (int)x is quickest.

    If x is a string but is definitely a valid number then int.Parse(x) is best

    If x is a string but it might not be valid then int.TryParse(x) is far quicker than a try-catch block.

    The difference between Parse and TryParse is negligible in all but the very largest loops.

    If you don't know what x is (maybe a string or a boxed int) then Convert.ToInt32(x) is best.

    These generalised rules are also true for all value types with static Parse and TryParse methods.

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

    Fastest != Best Practice!

    For example, (int) is almost certainly the fastest because it's an operator rather than a function call, but it will only work in certain situations.

    The best practice is to use the most readable code that won't negatively impact your performance, and 99 times out of 100 an integer conversion isn't driving your app's performance. If it is, use the most appropriate, narrowest conversion you can. Sometimes that's (int). Sometimes it's TryParse(). Sometimes it's Convert.ToInt32().

    0 讨论(0)
提交回复
热议问题