What is the fastest (built-in) comparison for string-types in C#

前端 未结 8 1517
南方客
南方客 2021-02-05 02:09

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

8条回答
  •  生来不讨喜
    2021-02-05 02:39

    I think there's a few ways most C# developers go about comparing strings, with the following being the most common:

    • Compare - as you mentioned
    • CompareOrdinal - as you mentioned
    • ==
    • String.Equals
    • writing a custom algorithm to compare char by char

    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. :-)

提交回复
热议问题