What is the fastest built-in comparison-method for string-types in C#? I don't mind about the typographical/semantical meaning: the aim is to use the comparator in sorted lists in order to search fast in large collections. I think there are only two methods: Compare
and CompareOrdinal
. What's the fastest?
Additionally, is there is a faster method for those string-comparisons?
I think there's a few ways most C# developers go about comparing strings, with the following being the most common:
Compare
- as you mentionedCompareOrdinal
- as you mentioned==
String.Equals
If you want to go to extremes, you can use other objects/methods that aren't so obvious:
SequenceEqual
example:c1 = str1.ToCharArray(); c2 = str2.ToCharArray(); if (c1.SequenceEqual(c2))
IndexOf
example:if (stringsWeAreComparingAgainst.IndexOf(stringsWeWantToSeeIfMatches, 0 , stringsWeWantToSeeIfMatches.Length) == 0)
Or you can implement Dictionary and HashSets, using the strings as "keys" and testing to see if they exist already with the string you want to compare against. For instance:
if (hs.Contains(stringsWeWantToSeeIfMatches))
So feel free to slice and dice to find your own ways of doing things. Remember though someone is going to have to maintain the code and probably won't want to spend time trying to figure out why you're using whatever method you've decided to use.
As always, optimize as your own risk. :-)
I designed a unit test to test string comparison speed using some of the methods mentioned in this post. This test was ran using .NET 4
In short, there isn't much much difference, and I had to go to 100,000,000 iterations to see a significant difference. Since it seems the characters are compared in turn until a difference is found, inevitably how similar the strings are plays a part.
These results actually seem to suggest that using str1.Equals(str2) is the fastest way to compare strings.
These are the results of the test, with the test class included: