Use vbNullString instead of "" - danielep71/VBA-PERFORMANCE GitHub Wiki

[Home]] ](/danielep71/VBA-PERFORMANCE/wiki/[[Tips-and-Tricks)


1. Statement

Using vbNullString is faster than “” to test empty strings.

2. Description

The “vbNullString” is a constant.

It occupies less memory (2 bytes) than a zero-length string denoted by “” (8 bytes), and it should be faster to process and assign.


Example:

MyString = vbNullString

is slightly more efficient than

MyString = “”


3. Performance test

Sub Test_vbNullString()
'------------------------------------------------------------------------------
'Declare
    Dim i               As Long                     'Loop counter
    Dim MyString        As String                   'Test String
    Dim MaxIter         As Long                     'Max # of iterations
    Dim iMethod         As Integer                  'Performance method
    Dim cPM             As cPerformanceMonitor      'Performance tracker
'------------------------------------------------------------------------------
'Initialize
    MaxIter = 100000000
    iMethod = 5
    Set cPM = New cPerformanceMonitor
'------------------------------------------------------------------------------
'Test1
    MyString = "qwertyuiopasdfghjklzxcvbnm"
    cPM.StartTimer (iMethod)
    For i = 1 To MaxIter
        MyString = vbNullString
    Next i
    Debug.Print cPM.ElapsedTime(iMethod) & " - vbNullString"
'Test2
    MyString = "qwertyuiopasdfghjklzxcvbnm"
    cPM.StartTimer (iMethod)
    For i = 1 To MaxIter
        MyString = ""
    Next i
    Debug.Print cPM.ElapsedTime(iMethod) & " - empty string"
'------------------------------------------------------------------------------
'Exit
    Set cPM = Nothing
End Sub

4. Results

The results are the following (looping 100,000,000 times):

  • 00:00:00 - 723 ms - 136 µs - 700 ns - vbNullString
  • 00:00:02 - 988 ms - 848 µs - 200 ns - empty string

Using vbNullString instead of “” is about 4 times faster.

If we change the variable MaxIter to 1, we can notice that the difference is only about a few microseconds:

  • 00:00:00 - 000 ms - 003 µs - 200 ns - vbNullString
  • 00:00:00 - 000 ms - 007 µs - 100 ns - empty string

5. Conclusions

Impact: negligible

Unless we have to empty strings millions of times, the performance improvement is negligible.


[Home]] ](/danielep71/VBA-PERFORMANCE/wiki/[[Tips-and-Tricks)