在平时代码中,字符串比较的方式有==、string.Equals、string. Compare。本文分别测试这三种方式的性能差别。
首先提供简单的测试方法:采用Stopwatch来测试执行的时间、GC.CollectionCount(0); GC.CollectionCount(1); GC.CollectionCount(2);反映托管区内存的分配情况。
测试代码如下:
运行环境 .NET4.0
1、性能测试方法:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public static void TestMethodPerformance<T>(Action<T> 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 }
2、被测的方法:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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 }
运行结果:
结论:
从运行结果可以看出 ==和string.Equals这两者的性能没什么差别。