Alex Rivera | Logout

Is it more efficient to compare ints and ints or strings and strings

Asked 2009-10-29T10:05:03.310
10

I've got a program written in c# where there are a lot of comparisons between ints and strings.

So for performance reasons, I would just like to know which is more efficient?

If we have:

int a  = 5;
string b = "5";

if(a == int.Parse(b)) { }

OR

if(a.ToString() == b) { }
Edit
Report

2 Answers

4

Your choice is between the following
Code Listing A

int a = 5;
string b = "5";
//Assuming these two values are input received by the application at runtime
int bInt;
if (int.TryParse(b, NumberStyles.None, CultureInfo.InvariantCulture, out bInt) 
    && a.Equals(bInt))
{

}

and

Code Listing B

int a = 5;
string b = "5"; 
//Assuming these two values are input received by the application at runtime
if (string.Compare(b, a.ToString(), StringComparison.Ordinal) != -1)
{

}

I have tested this with stopwatch (as given in the selected answer) and found Code Listing A to be much faster. But Code Listing B is more readable!

Code Listing A beats if(a == int.Parse(b))

answered 2009-10-29T10:49:25.873
1

The larger the number I'll go for the first method. a. if b is not a number, it will failed before trying to compare. b. string are compared by the length and number at once.

answered 2009-10-29T10:10:15.720

Your Answer