What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleCompare the speed of using Dim versus Dim As New
KeywordsDim, Dim As New, As New, declaration, performance
CategoriesTips and Tricks
When you declare a variable Dim X As New ..., Visual Basic doesn't actually initialize the variable until it uses it. Every time you refer to the variable Visual Basic needs to see if the variable has been initialized and initialize it if it hasn't. It essentially does something like this:

    If X Is Nothing Then allocate X
    Now do what the program says

The idea is Visual Basic cannot really know apriori whether the variable has been allocated yet.

If you declare the variable and initilize it separately, Visual Basic assumes you know what you're doing and that you will allocate the variable before you use it. If you don't, it raises an error.

This code creates two object variables. The variable emp1 is declared As New while variable emp2 is declared and initialized in separate statements. The program then references the objects' properties many times in loops. In my tests, Dim As New took about 20 percent longer than separate declaration and assignment statements.

Either way is still very fast, however, so for most programs it's not worth worrying about. On my computer, I had to repeat the loops 10 million times to get a consistent meaningful result. The difference is roughly 0.00000004 seconds per object reference. It's just not that much time.

Private Sub cmdGo_Click()
Dim num_trials As Long
Dim start_time As Single
Dim stop_time As Single
Dim i As Long
Dim emp1 As Employee
Dim emp2 As New Employee

    lblDim.Caption = ""
    lblDimAsNew.Caption = ""
    Screen.MousePointer = vbHourglass

    num_trials = CLng(txtTrials.Text)

    start_time = Timer
    Set emp1 = New Employee
    emp1.IsManager = False
    For i = 1 To num_trials
        If emp1.IsManager Then Stop
    Next i
    stop_time = Timer
    lblDim.Caption = Format$(stop_time - start_time, _

    start_time = Timer
    emp2.IsManager = False
    For i = 1 To num_trials
        If emp2.IsManager Then Stop
    Next i
    stop_time = Timer
    lblDimAsNew.Caption = Format$(stop_time - start_time, _

    Screen.MousePointer = vbDefault
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.