Reputation: 850
In VB6, I was told that when testing for an empty string, it would be much faster to check this by verifying the length of the string by using :
If Len("ABC") = 0 then 'fast
or
If LenB("ABC") = 0 then 'even faster
instead of:
If "ABC" = "" then 'slower
Do you know by any chance if this is true also in VB.NET? Thank you.
Upvotes: 3
Views: 5822
Reputation: 704
I don't exactly the syntax for VB but in C# you can use the String static method IsNullOrEmpty
:
String.IsNullOrEmpty("ABC")
When you are debugging this method, it will check on the .Length of the parameter. Checking on Length is always faster because on String compare, the compiler must create a new object to compare (in this case a "ABC" string).
Upvotes: 11
Reputation:
I think the the best solution for a VB6 equivalent to IsNullOrEmpty is
Public Function IsNullOrEmpty(ByRef s As Variant) As Boolean
If IsNull(s) Then ' IsNull returns true if s is a Variant that is Null
IsNullOrEmpty = True ' IsNull returns false if s is a Variant and s = vbEmpty
Exit Function
End If
If LenB(s) = 0 Then ' never compare a string to "" - it's slow
IsNullOrEmpty = True
Exit Function
End If
If LenB(Trim(s)) = 0 Then
IsNullOrEmpty = True
Exit Function
End If
IsNullOrEmpty = False
End Function
Ironically, if you have strings or variant that are set to vbEmpty, then this function will return false, because vbEmpty as string is "0". So if you are not careful using this version you could get some strange errors.
Upvotes: 0
Reputation: 4363
It's not necessary no, I mean are you kidding me? How many people write programs where comparing a string to see if it is zero length has any impact at all on performance. Even if strings didn't retain a length count and VB did a c-style strcmp() string comparison every time, it doesn't take a string comparison function very long to work out that one of the strings is zero length does it? But .NET strings do include a length field and so when you do a string comparison the first thing it's going to check is if the lengths differ, i.e. a straight int comparison. All you save by doing this yourself if a function call and then only if the JIT inlines Len().
By the way, in VB.NET you don't need to call String.IsNullOrEmpty() because comparisons between strings are transformed into a call to String.strcmp() which transforms nulls (Nothing in VB) into references to String.EmptyString. It then goes on to call a native function that Reflector can't examine, but I'd be pretty sure that the first thing it does is check if the lengths of the strings differ.
Upvotes: 5