liyonghui

导航

String.IsNullOrEmpty和"".length>0 那个更高效

今天在浏览DevTopics的博客时,发现一篇介绍String的随笔,介绍的是判断一个String变量是否为空时,String的一个方法和一个属性之间的比较,给一个 string变量 's', 下面那个表达式更快?

1. String.IsNullOrEmpty( s ) 
2. s == null || s.Length == 0 

如果你猜第二个,那么你是对的. 它将比String.IsNullOrEmpty方法快15%,但这种也是以百万分之一秒来衡量的!
这里有一个简单的例子来比较2种方式:

01using System;
02   
03namespace StringNullEmpty
04{
05class Program
06{
07static void Main( string[] args )
08{
09long loop = 100000000;
10string s = null;
11long option = 0;
12long empties1 = 0;
13long empties2 = 0;
14   
15 DateTime time1 = DateTime.Now;
16   
17for (long i = 0; i < loop; i++)
18{
19 option = i % 4;
20switch (option)
21{
22case 0:
23 s = null;
24break;
25case 1:
26 s = String.Empty;
27break;
28case 2:
29 s = "H";
30break;
31case 3:
32 s = "HI";
33break;
34}
35if (String.IsNullOrEmpty( s ))
36 empties1++;
37}
38   
39 DateTime time2 = DateTime.Now;
40   
41for (long i = 0; i < loop; i++)
42{
43 option = i % 4;
44switch (option)
45{
46case 0:
47 s = null;
48break;
49case 1:
50 s = String.Empty;
51break;
52case 2:
53 s = "H";
54break;
55case 3:
56 s = "HI";
57break;
58}
59if (s == null || s.Length == 0)
60 empties2++;
61}
62   
63 DateTime time3 = DateTime.Now;
64   
65 TimeSpan span1 = time2.Subtract( time1 );
66 TimeSpan span2 = time3.Subtract( time2 );
67 Console.WriteLine( "(String.IsNullOrEmpty( s )): Time={0} Empties={1}",
68 span1, empties1 );
69 Console.WriteLine( "(s == null || s.Length == 0): Time={0} Empties={1}",
70 span2, empties2 );
71 Console.ReadLine();
72}
73}
74}

 一般我喜欢定义成这样:string a=string.Empty;不用判断是否为null。

posted on 2011-08-08 11:55  李永辉  阅读(822)  评论(0编辑  收藏  举报