Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why not to use the "Dim myObj as New Object" construct

VB Programming Concepts

Why not to use the "Dim myObj as New Object" construct

by  BobRodes  Posted    (Edited  )
In Java, C#, and VB.Net, using the New keyword on the same line as the declaration statement actually causes the object to be instantiated. Not so with VB6. In VB6, the As New syntax creates an "auto-instancing" object variable. In other words, the code line
Code:
Dim myObj as New myClass
requires the VB compiler, every time myObj is referenced, to check and see if myObj is Nothing and if so to create an instance of myClass. So, the code
Code:
Dim myObj as New myClass
myObj.Prop1 = "SomeValue"
myObj.Prop2 = "SomeOtherValue"
myObj.MyMethod1
myObj.MyMethod2
requires the compiler to check four times whether an object has been instantiated. This represents unnecessary code overhead.

Writing the code in this way
Code:
Dim myObj as myClass
Set myObj = New myClass
myObj.Prop1 = "SomeValue"
myObj.Prop2 = "SomeOtherValue"
myObj.MyMethod1
myObj.MyMethod2
removes this overhead.

While there are some circumstances in which the use of the former syntax is preferable to the latter, they are few and far between. For example, if you had a large number of instances of another object that only in certain circumstances ever used this object, and when they did only called one method of the object one time, it might make sense not to instantiate the object unless the code referenced it to avoid unnecessary memory overhead.

However, the time that you will see this most often is when the object is only referenced once, especially in conjuction with the With keyword. For example:
Code:
Dim myObject as New myClass
With myObject
   .ThisProperty = SomeValue
   .ThatProperty = SomeOtherValue
   .AndSoOn = SomethingElse
End With
This will only actually instantiate the object once, at the time it is encountered in the with statement. Of course, you don't really need to use a myObject variable in this case; it's more a matter of style. You can also do it this way:
Code:
With New myClass
   .ThisProperty = SomeValue
   .ThatProperty = SomeOtherValue
   .AndSoOn = SomethingElse
End With
In effect, this is also an auto-instancing variable, since an instantiated class reference is implied (and created) by the "with new" statement. This is actually even more efficient, as it isn't storing a variable definition throughout the life of the procedure in which it's declared.

Bob
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top