使用ToUpperInvariant避免使用ToUpper

ToUpperInvariant使用不依赖于区域性进行转换,而ToUpper则使用了当前线程的CultureInfo,进行转换,所以性能会有所影响,以下为测试:

 1         [Test]
 2         public void TestInvariant()
 3         {
 4             Int32 count = 1000 * 1000;
 5             Stopwatch watch = new Stopwatch();
 6 
 7             String str = "abcdefghijklmnopqrstuvwxyz中华人民共和国";
 8             watch = Stopwatch.StartNew();
 9             for (int i = 0; i < count; i++)
10             {
11                 str.ToUpperInvariant();
12             }
13             Console.WriteLine("ToUpperInvariant:{0}", watch.Elapsed.ToString());
14         }
15 
16         [Test]
17         public void TestNoInvariant()
18         {
19             Int32 count = 1000 * 1000;
20             Stopwatch watch = new Stopwatch();
21 
22             String str = "abcdefghijklmnopqrstuvwxyz中华人民共和国";
23             watch = Stopwatch.StartNew();
24             for (int i = 0; i < count; i++)
25             {
26                 str.ToUpper();
27             }
28             Console.WriteLine("ToUpper:{0}", watch.Elapsed.ToString());
29         }

 

ToUpperInvariant:00:00:00.2980660

ToUpper:00:00:00.3281423

如果 确认当前的比较和区域性无关的话,推荐使用ToUppperInvariant

posted @ 2013-09-04 17:55  小R  阅读(490)  评论(0编辑  收藏  举报