在平時代碼中,字符串比較的方式有==、string.Equals、string. Compare。本文分別測試這三種方式的性能差別。
首先提供簡單的測試方法:採用Stopwatch來測試執行的時間、GC.CollectionCount(0); GC.CollectionCount(1); GC.CollectionCount(2);反映託管區內存的分配情況。
測試代碼如下:
運行環境 .NET4.0
1、性能測試方法:
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、被測的方法:
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這兩者的性能沒什麼差別。