Hi Greg
It's a typo. It should of course have been:
If LenB(strTest) = 0 Then
When typing the worst to best list out I actually missed one out, here's the corrected
list:
If strTest = "" Then
If strTest = vbNullString Then
If Len(strTest) = 0 Then
If LenB(strTest) = 0 Then
The performance gain (try a million of so loops! ) comes from the fact that no string
comparison is actually performed! String are pointer types in VBA/VB, in other words what
you think of as your string variable (in our case strTest) is actually a pointer to part
of a BSTR structure. The BSTR structure contains the null terminated string (in unicode,
2 bytes per character including the null terminator) prefixed by a Long (4 bytes)
indicating the length of the string.
Using Len or better still LenB causes VBA only looks at the length part of strings BSTR
structure, rather than performing a string compare. The reason that vbNullString is
considered better than "", is that "" takes up 6 bytes of memory (4 bytes for the string
length and 2 for the null terminator character), whereas vbNullString is just a NULL
string-pointer. In other words there's no allocated string when using vbNullString.
I hope this makes some sense, even if it doesn't instead of writing:
If strTest = "" Then
use:
If LenB(strTest) = 0 Then
and don't bother with understanding why!
Cheers - Peter
Peter,
Your are the teacher, I am the student. What do you mean by "effectively
equal?" I ran this test:
Sub Test()
Dim strTest
strTest = ""
If strTest = "" Then
MsgBox "Check"
If strTest = vbNullString Then
MsgBox "Check"
If LenB(strTest) = vbNullString Then
MsgBox "Check"
Else: MsgBox "Houston Control we have a problem"
End If
End If
End If
End Sub
The third expression acts differently. The value is "0" rather than ""
HTH + Cheers - Peter