vbaoptimizationprofilingcompiler-optimization

Does the Native VBA Compiler Optimize?


My code is as follows:

#Const debuggingEnabled = False

Sub debugMessage(str As String)
    #If debuggingEnabled Then
        Debug.Print str
    #End If
End Sub

Sub doThings()
    debugMessage "test"   'Does this get optimised away, or must it be explicitly
                          'wrapped with `#If .. #End If` every time it's called
                          'if one is to avoid the jump and stack push/pop ops?
End Sub

Does Microsoft's VBA compiler optimise away calls to procedures that do nothing? How can I find out?


Solution

  • Upgrading this from comment to answer:

    What is the point in "optimizing away" a procedure containing a single, one-bit, binary, boolean test? Are you sure that this represents a significant portion of execution time? The chances of that are pretty remote.

    Before optimizing, always do some profiling, so you don't waste time and worry on bits of code that represent 0.0001% of your execution time.

    VBA has no native profiler, but there are third-party options out there, some of them free. This is one, accompanied by an instructive read: Profiling and Optimizing VBA By bruce mcpherson. A DuckDuckGo search gives plenty of other leads as well.

    So, the answer to your original question is: I don't think VBA optimizes such a procedure away, but I'm not entirely sure, and either way it is in all likelihood completely irrelevant. Before worrying about optimizing, always do some profiling, so you can spend your time wisely. After profiling, you will almost always find that what you thought slowed down your program is actually very fast, and that something else is the culprit.