[Performance][VB.NET].NET空字串判斷徹底研究
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }]]> 執行結果如下:從上圖可看出幾個現象用String.IsNullOrEmpty同時判斷Nothing與空字串會比只判斷是否為 Nothing 或為空還慢當字串不為 Nothing 時要判斷字串是否為空的話,用Is String.Empty去判斷最快(文件上通常是說String.Length = 0最快) 接著再看個實驗來看當同時判斷Nothing與空字串的情況,測試程式如下: Sub Main() Dim testStrings() As String = New String() {Nothing, "", String.Empty} For Each str As String In testStrings ‘TestString(str) TestStringSpeed(str, 10000000) Console.WriteLine("=======================") Next End Sub Private Sub TestStringSpeed(ByVal str As String, ByVal count As Integer) Dim n As Integer = count Dim sw As New Stopwatch Console.WriteLine(“str Is Nothing & Is String.Empty”) sw.Start() For i As Integer = 1 To n If str Is Nothing Then Else If str Is String.Empty Then End If End If Next Console.WriteLine(“花費時間: “ & sw.ElapsedMilliseconds) Console.WriteLine(“str Is Nothing & Is String.Empty”) sw.Reset() sw.Start() For i As Integer = 1 To n If str Is Nothing Then Else If str.Length = 0 Then End If End If Next Console.WriteLine(“花費時間: “ & sw.ElapsedMilliseconds) If str = Nothing Then Console.WriteLine(“str = Nothing”) sw.Reset() sw.Start() For i As Integer = 1 To n If str = Nothing Then End If Next Console.WriteLine(“花費時間: “ & sw.ElapsedMilliseconds) Console.WriteLine(“str = “”"”") sw.Reset() sw.Start() For i As Integer = 1 To n If str = ”" Then End If Next Console.WriteLine(“花費時間: “ & sw.ElapsedMilliseconds) Console.WriteLine(“str = String.Empty”) sw.Reset() sw.Start() For i As Integer = 1 To n If str = String.Empty Then End If Next Console.WriteLine(“花費時間: “ & sw.ElapsedMilliseconds) Console.WriteLine(“String.IsNullOrEmpty(str)") sw.Reset() sw.Start() For i As Integer = 1 To n If String.IsNullOrEmpty(str) Then End If Next Console.WriteLine(“花費時間: “ & sw.ElapsedMilliseconds) End Sub 執行結果如下: 可以看出 String.IsNullOrEmpty 函式的效能與自行混用 str Is Nothing 與 Is String.Empty 判斷方法來達到相同目的的效能差不多。經過以上三個實驗,對於字串為空的判斷相信已有相當的了解,若能清楚分辨其功用與使用的時機,多少都能增進程式的效能。像是使用上若只需判斷Nothing或為空的話,應避免誤用會同時判斷的方法(如下例),就可以避免不必要的OverHead。