Which is fast comparison: Convert.ToInt32(stringValue)==intValue or stringValue==intValue.ToString()

后端 未结 8 2071
执念已碎
执念已碎 2021-02-13 18:34

While developing my application i came across some comparison stuff here was it:

    string str = \"12345\";
    int j = 12345;
    if (str == j.ToString())
             


        
8条回答
  •  别那么骄傲
    2021-02-13 19:17

    Your test is fundamentally flawed. The compiler and run-time are really clever beasts and will optimise the code both at compile time and run time (JIT-ing). In this case, you are doing the same thing every time which will be spotted by the compiler and optimised out, hence the timing will be similar for each method.

    Try this version (I've only got .Net 2.0, hence the slight changes):

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Diagnostics;
    
    namespace ToStringTest
    {
        class Program
        {
            const int
                iterationCount = 1000000;
    
            static TimeSpan Test1()
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                string str = "12345";
                int j = 12345;
                for (int i = 0; i < iterationCount; i++)
                {
                    if (str == i.ToString())
                    {
                        //do my logic
                    }
                }
                watch.Stop();
                return watch.Elapsed;
            }
    
            static TimeSpan Test2()
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                string str = "12345";
                int j = 12345;
                for (int i = 0; i < iterationCount; i++)
                {
                    if (Convert.ToInt32(i) == j)
                    {
                        //do my logic
                    }
                }
                watch.Stop();
                return watch.Elapsed;
            }
    
            static void Main(string[] args)
            {
                Console.WriteLine("ToString = " + Test1().TotalMilliseconds);
                Console.WriteLine("Convert = " + Test2().TotalMilliseconds);
            }
        }
    }
    

    and you will see a huge difference. One is two orders of magnitude faster than the other. And it really is obvious which one it is.

    You need to know what the various operations are doing in order to know which is fundamentally faster.

    Converting a string to an int requires the following:

    total = 0
    for each character in string
      total = total * 10 + value of charater
    

    and the ToString requires:

    string = ""
    while value != 0
      string.AddToFront value % 10
      value /= 10
    

    Multiplication is far easier, and faster, for a CPU to do than division. Given the choice of an algorithm with lots of multiplies versus an algorithm with lots of divides, always go for the former as it will always be faster.

    Then there's the comparison, an int - int comparison is simple, load each value into a register and compare - a couple of machine instructions and you're done. A comparison between two strings requires testing each character in the strings one at a time - in the example you gave it was 5 bytes (an int is probably 4 bytes) which is more memory accesses.

提交回复
热议问题