C #, string comparison operation

C #, string comparison operation

https://www.cnblogs.com/junbird-nest/archive/2012/03/23/2413557.html

String comparison operation is more commonly used, generally for two reasons compare strings:

  • For equality
  • String sorting

API query string for equality or sorted, by the following method:

 

      public override bool Equals(object obj);
        public bool Equals(string value);
        public static bool Equals(string a, string b);
        public bool Equals(string value, StringComparison comparisonType);
        public static bool Equals(string a, string b, StringComparison comparisonType);

        public static int Compare(string strA, string strB);
        public static int Compare(string strA, string strB, bool ignoreCase);
        public static int Compare(string strA, string strB, StringComparison comparisonType);
        public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture);
        public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options);
        public static int Compare(string strA, int indexA, string strB, int indexB, int length);
        public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
        public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
        public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture);
        public static int Compare(string strA, int indexA, string strB, int indexB, int length, CultureInfo culture, CompareOptions options);

        public static int CompareOrdinal(string strA, string strB);
        public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length);

        public int CompareTo(object value);
        public int CompareTo(string strB);

Found in most of the above methods have StringComparison type of enumeration, get the inquiry msdn:

stringComparison

Now write a simple piece of code, test Compare (string strA, string strB, StringComparison comparisonType) method. They were used StringComparison.CurrentCulture and StringComparison.Ordinal. code show as below:

      static void Main(string[] args)
       {
           string strA = "asdfadsfasdfew我ò啊?地?方?的?asd";
           string strB = "adsfeaqfaead啊?多à发¢安2德?森-efadsfa";
           Stopwatch sw = new Stopwatch();

           sw.Start();
           for (int i = 0; i < 1000000; i++)
           {
               string.Compare(strA, strB, StringComparison.CurrentCulture);
           }
           sw.Stop();
           Console.WriteLine(sw.ElapsedMilliseconds);
           
           sw.Reset();
           for (int i = 0; i < 1000000; i++)
           {
               string.Compare(strA, strB,StringComparison.Ordinal);
           }
           sw.Stop();
           Console.WriteLine(sw.ElapsedMilliseconds);

           sw.Reset();
           for (int i = 0; i < 1000000; i++)
           {
               string.CompareOrdinal(strA, strB);
           }
           sw.Stop();
           Console.WriteLine(sw.ElapsedMilliseconds);
       }

Execution results are as follows:

result

Test results are very obvious, StringComparison.Currentculture explicitly pass the current language and culture, and passed String.Ordinal will ignore the specified language and culture, which is one of the fastest way to perform string.

Use .NET Reflector to view the source code:

public static int Compare(string strA, string strB, StringComparison comparisonType)
        {
            if ((comparisonType < StringComparison.CurrentCulture) || (comparisonType > StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
            }
            if (strA == strB)
            {
                return 0;
            }
            if (strA == null)
            {
                return -1;
            }
            if (strB == null)
            {
                return 1;
            }
            switch (comparisonType)
            {
                case StringComparison.CurrentCulture:
                    return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);

                case StringComparison.CurrentCultureIgnoreCase:
                    return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);

                case StringComparison.InvariantCulture:
                    return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);

                case StringComparison.InvariantCultureIgnoreCase:
                    return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);

                case StringComparison.Ordinal:
                    return CompareOrdinalHelper(strA, strB);

                case StringComparison.OrdinalIgnoreCase:
                    if (!strA.IsAscii() || !strB.IsAscii())
                    {
                        return TextInfo.CompareOrdinalIgnoreCase(strA, strB);
                    }
                    return CompareOrdinalIgnoreCaseHelper(strA, strB);
            }
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_StringComparison"));
        }
In the above example, while the String CompareOrdinal tested methods, the same surprising efficiency. After a review of the source code and find the Compare method String.Ordinal source code, this method is just a special case of the Compare method:
 
public static int CompareOrdinal(string strA, string strB)
        {
            if (strA == strB)
            {
                return 0;
            }
            if (strA == null)
            {
                return -1;
            }
            if (strB == null)
            {
                return 1;
            }
            return CompareOrdinalHelper(strA, strB);
        }

 

 

Next, look at the source String.compareTo () method:

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
       public int CompareTo(string strB)
       {
           if (strB == null)
           {
               return 1;
           }
           return CultureInfo.CurrentCulture.CompareInfo.Compare(this, strB, CompareOptions.None);
       }

The same type of parameters StringComparison.CurrentCulture Compare method.

 

 

Further StringComparer string comparison method also implements the Compare () method. Direct look at the source code:

public int Compare(object x, object y)
      {
          if (x == y)
          {
              return 0;
          }
          if (x == null)
          {
              return -1;
          }
          if (y == null)
          {
              return 1;
          }
          string str = x as string;
          if (str != null)
          {
              string str2 = y as string;
              if (str2 != null)
              {
                  return this.Compare(str, str2);
              }
          }
          IComparable comparable = x as IComparable;
          if (comparable == null)
          {
              throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
          }
          return comparable.CompareTo(y);
      }

 

 

If the program is only for internal string encoding, such as path name, file name, URL, environment variables, reflection, XML markings, these strings are usually only in the use of internal procedures, the user does not like the show, you should use String. Ordinal or use String.CompareOrdinal () method

 

Summary and Recommendations:

  1. Show the use of overloaded functions specified string comparison rules. In general, with the required parameters of the type overloads StringComparison
  2. When compared to the string unknown culture, and StringComparison.OrdinallgnoreCase StringComparison.Ordinal use as a default, to improve performance
  3. When a user as output, a string-based StringComparison.CurrentCulture
  4. Use heavy-duty version String.Equals to test whether two strings are equal.
  5. Do not use a heavy duty version String.Compare CompareTo or to detect the return value is equal to 0 to determine whether the string. These two functions are used for string comparison, rather than be checked for equality.
  6. When comparing strings, the strings should be standardized String.ToUpperInvariant function without ToLowerInvariant method, because Microsoft code execution capital of comparison were optimized. Why do not ToUpper and ToLower method, because of its sensitivity to language and culture.

 

 

 

 

 

Published 80 original articles · won praise 38 · views 40000 +

Guess you like

Origin blog.csdn.net/kuangben2000/article/details/104676667