Friday, January 25, 2008

String Comparison in C#, an interesting topic !

There are many ways of string comparison in C#. Following are some of them:

1. Using ==

2. Using String.Equals(a, b)

3. Using Object.Equals(a, b)

4. Using String.Compare(a, b)

5. Using a.Equals(b)

Here both a and b are string variables.

The overloaded == operator and String.Equals are equal in speed. The Object.Equals is slightly slower because it is virtual in nature. If Equals method is used, then String.Equals is a better option than Object.Equals. The a.Equals(b) is more slower than the earlier, but this is only significant in very large numbers of equality checks.

All the options 1, 2, 3 and 5 check the equality from the string content, rather than the reference. The option 3 is calling the
String.Equals because Equals is a virtual function.

String.Compare in other hand is totally different and it is not used for the same purpose. It is much slower than all other methods when checking if the strings are equal. All others check if the strings are equal, but the String.Compare, compares the strings more deeply and returns a number which indicates the lexical relationship between the two strings, so it is not really advised to use String.Compare when just checking if the strings contain the same text i.e. checking if the strings are equal.

Comments are Welcome :)


Post a Comment