Anoj said:
Hi All ,
can anyone tell me what is the difference between the following declaration
and how it affects
application performance.
1.
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
2. Dim cn As New ADODB.Connection
Since your using Set, I have to assume that this is VB6 code. If that
is the case, there is a subtle difference and the first option is
usually the prefered method. The difference is mainly as to when the
intialization of the object takes place. With the As New syntax,
initialization is delayed until the first reference to the object. In
other words:
Dim o As New MyObjectType ' o is not created here
' Do Cool Stuff
.....
o.ExecuteAMethod() ' o is created and then the method called.
The main problem with this behavior is that, not only does it introduce
some very subtle bugs, but it can adversely affect performance since VB
is forced to check the integrity of the reference every time you use
it... For example if you have an object declared this way in a loop,
and then you call a whole bunch of methods/properties you end up
generating something like this around every call:
If o Is Nothing Then
Set o = New MyObject
o.ExecuteTheMethod()
Else
o.ExecuteTheMethod()
End If
Anyway, the point is that this can be an expensive operation. The bugs
come into play when you have something like this:
Dim f As New Form
' do stuff with f
Set f = Nothing
If f Is Nothing Then
MsgBox "The Form Is Nothing"
Else
MsgBox "Hey, Form Still Exists!"
End If
In the above code, the mere act of testing f for nothing causes it to be
reinstantiated - resulting in zombi-like behavior for objects crated "As
New". Basically, it is usually considered bad practice to use this form
of declaration in VB.
Now, if you were talking VB.NET and somehow just slipped in the Set -
well then ignore all of the above, since this isn't true in VB.NET.
VB.NET intializes the object at the point of the As New. The net result
is that there is no effective difference between:
Dim o As SomeObject
o = New SomeObject()
And
Dim o As New SomeObject
HTH,
Tom Shelton