C#性能之字符串比较

在平时代码中,字符串比较的方式有==、string.Equals、string. Compare。本文分别测试这三种方式的性能差别。

首先提供简单的测试方法:采用Stopwatch来测试执行的时间、GC.CollectionCount(0); GC.CollectionCount(1); GC.CollectionCount(2);反映托管区内存的分配情况。

测试代码如下:

运行环境 .NET4.0

1、性能测试方法:

 1  public static void TestMethodPerformance(Action action, T t, int times)
 2         {
 3             int startGc0 = GC.CollectionCount(0);
 4             int startGc1 = GC.CollectionCount(1);
 5             int startGc2 = GC.CollectionCount(2);
 6 
 7             Stopwatch stopwatch = Stopwatch.StartNew();
 8             for (int i = 0; i < times; i++)
 9             {
10                 action(t);
11             }
12             stopwatch.Stop();
13             int endGc0 = GC.CollectionCount(0);
14             int endGc1 = GC.CollectionCount(1);
15             int endGc2 = GC.CollectionCount(2);
16 
17             Console.WriteLine("耗时:" + stopwatch.ElapsedMilliseconds + " ms");
18             Console.WriteLine("第0代回收次数:" + (endGc0 - startGc0));
19             Console.WriteLine("第1代回收次数:" + (endGc1 - startGc1));
20             Console.WriteLine("第2代回收次数:" + (endGc2 - startGc2));
21         }
View Code

2、被测的方法:

 1 private static void Main(string[] args)
 2         {
 3             string temp = "TestTestTest";
 4 
 5             MethodTest.TestMethodPerformance(StringEqual_1, temp, 100000);
 6             MethodTest.TestMethodPerformance(StringEqual_2, temp, 100000);
 7             MethodTest.TestMethodPerformance(StringEqual_3, temp, 100000);
 8             Console.ReadLine();
 9         }
10 
11         private static void StringEqual_1(string temp)
12         {
13             if (string.Equals(temp, "TestTestTest"))
14             {   
15             }
16            
17         }
18 
19         private static void StringEqual_2(string temp)
20         {
21             if (temp == "TestTestTest")
22             {
23             }
24         }
25 
26         private static void StringEqual_3(string temp)
27         {
28             if (string.Compare(temp, "TestTestTest", true) > 0)
29             {
30             }
31         }
View Code

运行结果:

C#性能之字符串比较_第1张图片

 

结论:

从运行结果可以看出 ==和string.Equals这两者的性能没什么差别。

转载于:https://www.cnblogs.com/jintianzhang/archive/2013/05/27/3102822.html

你可能感兴趣的:(C#性能之字符串比较)