今天在浏览DevTopics的博客时,发现一篇介绍String的随笔,介绍的是判断一个String变量是否为空时,String的一个方法和一个属性之间的比较,给一个 string变量 's', 下面那个表达式更快?
1. String.IsNullOrEmpty( s )
2. s == null || s.Length == 0
如果你猜第二个,那么你是对的. 它将比String.IsNullOrEmpty方法快15%,但这种也是以百万分之一秒来衡量的!
这里有一个简单的例子来比较2种方式:
01 | using System; |
02 | |
03 | namespace StringNullEmpty |
04 | { |
05 | class Program |
06 | { |
07 | static void Main( string [] args ) |
08 | { |
09 | long loop = 100000000; |
10 | string s = null ; |
11 | long option = 0; |
12 | long empties1 = 0; |
13 | long empties2 = 0; |
14 | |
15 | DateTime time1 = DateTime.Now; |
16 | |
17 | for ( long i = 0; i < loop; i++) |
18 | { |
19 | option = i % 4; |
20 | switch (option) |
21 | { |
22 | case 0: |
23 | s = null ; |
24 | break ; |
25 | case 1: |
26 | s = String.Empty; |
27 | break ; |
28 | case 2: |
29 | s = "H" ; |
30 | break ; |
31 | case 3: |
32 | s = "HI" ; |
33 | break ; |
34 | } |
35 | if (String.IsNullOrEmpty( s )) |
36 | empties1++; |
37 | } |
38 | |
39 | DateTime time2 = DateTime.Now; |
40 | |
41 | for ( long i = 0; i < loop; i++) |
42 | { |
43 | option = i % 4; |
44 | switch (option) |
45 | { |
46 | case 0: |
47 | s = null ; |
48 | break ; |
49 | case 1: |
50 | s = String.Empty; |
51 | break ; |
52 | case 2: |
53 | s = "H" ; |
54 | break ; |
55 | case 3: |
56 | s = "HI" ; |
57 | break ; |
58 | } |
59 | if (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。