string.CompareOrdinal(效率高),checked(检查溢出)

几种比较方法的效率 

            int num = 10000000;
            string str1 = "abcdaefvff";
            string str2 = "abcdsafsafed";
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            for(int i=0;i < num; i++)
            {
                string.CompareOrdinal(str1, str2);// StringComparison.Ordinal 使用序号排序规则比较字符串。
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);///84ms

            stopwatch.Restart();
            for (int i = 0; i < num; i++)
            {
                string.Compare(str1, str2);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);//2349ms

            stopwatch.Restart();
            for (int i = 0; i < num; i++)
            {
                string.Compare(str1, str2,StringComparison.Ordinal);//等效于 string.CompareOrdinal(str1, str2)
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);//86ms

            stopwatch.Restart();
            for (int i = 0; i < num; i++)
            {
                str1.CompareTo(str2);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);//2324ms
            Console.ReadKey();

可自行看反编译,为何 string.Compare(str1, str2,StringComparison.Ordinal)效率会比string.Compare(str1, str2

 

Checked


  int i=2147483647;
  int j=checked(i+1);


  checked
  {    
      int i=2147483647;  
      int j=m+1;   
  }
  

两种方式检查溢出,溢出后会抛异常,可避免 j 变成负数等不期望出现的值。

 

你可能感兴趣的:(c#)