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

后端 未结 8 2053
执念已碎
执念已碎 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 18:53

    I prefer i.ToString() == str since nothing guarantees that Convert.ToInt32(str) doesn't fail.

    0 讨论(0)
  • 2021-02-13 18:56

    Well - performance should not be the only thing that matters.

    You should ask whether you want to compare the actual value or only the representation of the number.

    Take the following example: Does "00001" equal 1? If you want it to convert the string to int using Int.TryParse in combination and then compare them.

    There might be other differences, too depending of the local settings. Maybe the user has set to format numbers like "1,000,000" - if you'd compare that string to 1000000.ToString() the result would be false.

    0 讨论(0)
  • 2021-02-13 18:57

    If performance is near identical, go with the version that is more readable.

    Personally, I find the .ToString() approach to be easier to understand and less prone to possible casting issues that the other approach has.

    0 讨论(0)
  • 2021-02-13 19:01

    Well for starters the first one which converts the int to a string won't throw an error if the string the int is being compared to isn't convertible to an int.

    If you are doing a lot of tests in a batch converting to a string will remove the problem of potentially having exceptions throw, because of conversion errors. Raising exceptions takes time and would slow down the second test.

    0 讨论(0)
  • 2021-02-13 19:02

    Okay, i further move one step ahead and test in this way:

        int j = 123;
        for (var i = 0; i < iterationCount; i++)
        {
            j.ToString();
        }
    

    second one: string str = "123";

            for (var i = 0; i < iterationCount; i++)
            {
                Convert.ToInt32(str);
            }
    

    In this case i found every time second one is performing a little better. In my case the number would be like 100000 only and not in the form of 100,000. Your comments on this test that i did in this post ??

    0 讨论(0)
  • 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.

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