Checking for string contents? string Length Vs Empty String

前端 未结 13 909
野趣味
野趣味 2020-12-17 10:14

Which is more efficient for the compiler and the best practice for checking whether a string is blank?

  1. Checking whether the length of the string == 0
13条回答
  •  执念已碎
    2020-12-17 10:44

    Assuming your question is .NET:

    If you want to validate your string against nullity as well use IsNullOrEmpty, if you know already that your string is not null, for example when checking TextBox.Text etc., do not use IsNullOrEmpty, and then comes in your question.
    So for my opinion String.Length is less perfomance than string comparison.

    I event tested it (I also tested with C#, same result):

    Module Module1
      Sub Main()
        Dim myString = ""
    
    
        Dim a, b, c, d As Long
    
        Console.WriteLine("Way 1...")
    
        a = Now.Ticks
        For index = 0 To 10000000
          Dim isEmpty = myString = ""
        Next
        b = Now.Ticks
    
        Console.WriteLine("Way 2...")
    
        c = Now.Ticks
        For index = 0 To 10000000
          Dim isEmpty = myString.Length = 0
        Next
        d = Now.Ticks
    
        Dim way1 = b - a, way2 = d - c
    
        Console.WriteLine("way 1 took {0} ticks", way1)
        Console.WriteLine("way 2 took {0} ticks", way2)
        Console.WriteLine("way 1 took {0} ticks more than way 2", way1 - way2)
        Console.Read()
      End Sub
    End Module
    

    Result:

    Way 1...
    Way 2...
    way 1 took 624001 ticks
    way 2 took 468001 ticks
    way 1 took 156000 ticks more than way 2
    

    Which means comparison takes way more than string length check.

提交回复
热议问题