none
Faster to compare ToString() or Equal()? RRS feed

  • Question

  • object o;

    string number;

     

    o is always of type (int)

     

    Question which is the faster compare:

     

    if (o.Equals(int.Parse(number)))

    {

     

    }

     

    or

     

    if (number.Equals(o.ToString()))

    {

     

    }

     

    Any suggestions on a faster way to compare would be great.

     

    Thanks.

    Monday, March 31, 2008 4:39 PM

Answers

  • Interesting question. There's only one way to find out: benchmark it.

     

    And the results are:

     

    Tested with the number 500 (10 million iterations):

    ToString() = 4.59 seconds

    Parse() = 4.44 seconds

     

    Tested with the number 5 (10 million iterations):

    ToString() = 3.73 seconds

    Parse() = 4.15 seconds

     

    Too close to call. For single digit numbers, ToString() is a little faster, for 3 digits, Parse() is a little faster

     

    But the difference is minimal.

     

    Monday, March 31, 2008 5:14 PM

All replies

  • Interesting question. There's only one way to find out: benchmark it.

     

    And the results are:

     

    Tested with the number 500 (10 million iterations):

    ToString() = 4.59 seconds

    Parse() = 4.44 seconds

     

    Tested with the number 5 (10 million iterations):

    ToString() = 3.73 seconds

    Parse() = 4.15 seconds

     

    Too close to call. For single digit numbers, ToString() is a little faster, for 3 digits, Parse() is a little faster

     

    But the difference is minimal.

     

    Monday, March 31, 2008 5:14 PM
  • Another thing to consider is that you won't necessarily get the same result from the two comparisons for all values of number.

     

    For example, o.Equals(int.Parse(number)) will return true and the other comparison false if o is = 1 and number contains a string  such as

    "+1"

    "001"

     

    Monday, March 31, 2008 7:03 PM
  • Thank you

     

    That helps.

    Monday, March 31, 2008 9:46 PM