C#性能之字符串比较

在平时代码中,字符串比较的方式有==、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         }
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

运行结果:

 

结论:

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值