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
I'm assuming you want a less-than/equal/greater-than comparison rather than just equality; equality is a slightly different topic, although the principles are basically the same. If you're actually only searching for presence in something like a SortedList
, I'd consider using a Dictionary
instead - do you really need all that sorting?
String.CompareOrdinal
, or using an overload of String.Compare
which allows the comparison to be provided, and specifying an ordinal (case-sensitive) comparison, e.g. String.Compare(x, y, StringComparison.Ordinal)
will be the fastest.
Basically an ordinal comparison just needs to walk the two strings, character by character, until it finds a difference. If it doesn't find any differences, and the lengths are the same, the result is 0. If it doesn't find any differences but the lengths aren't the same, the longer string is deemed "larger". If it does find a difference, it can immediately work out which is deemed "larger" based on which character is "larger" in ordinal terms.
To put is another way: it's like doing the obvious comparison between two char[]
values.
Culture-sensitive comparisons have to perform all kinds of tortuous feats, depending on the precise culture you use. For an example of this, see this question. It's pretty clear that having more complex rules to follow can make this slower.