
Originally Posted by
dilettante
I'd avoid As New and would use a With block here just to cut the cost a little more, though the latter doesn't matter much in this case. Some of it is habit and some is about the overhead of As New.
I'm aware of the implications of 'As New' definitions when I post examples.
That's perhaps another one of those "old ingrained rules" which deserve "a review" (also the With-Block-usage) -
at least in terms of performance there isn't any differences anymore when we call methods.
The As New defintion will cause the compiler, to enclose any occurence of the Obj-Variable with
"If Obj Is Nothing..." checks (which is just a check for a Zero-Pointer, which nowadays is
"optimized away" (not by the compiler, but by the larger and highly sophisticated Pipelines in
modern CPUs).
Here's a Test-Snippet, which (native compiled) doesn't show any differences among the three methods:
Into a Class, with default-naming Class1
Code:
Option Explicit
Public Function Reflect(ByVal Param As Long)
Reflect = Param
End Function
Into a Form, compile it natively - and then compare the 3 Values by clicking the Form
Code:
Option Explicit
Private Sub Form_Click()
Cls
DoEvents
Const LoopCount As Long = 10 ^ 7 '10 Mio calls against a small method
Dim i As Long, Result As Long, C1 As Class1, C2 As New Class1, C3 As Class1, T!
'first the explicit case
Set C1 = New Class1
T = Timer
For i = 1 To LoopCount
Result = C1.Reflect(i)
Next i
Print "explicit instancing: ", Format$((Timer - T) * 1000, "0.0msec")
DoEvents
'now the implicit instancing which performs an "Is Nothing" check under the hood (if the ObjPtr is Zero)
T = Timer
For i = 1 To LoopCount
Result = C2.Reflect(i)
Next i
Print "implicit instancing: ", Format$((Timer - T) * 1000, "0.0msec")
DoEvents
'finally a With-construct on a explicitely instanciated class
Set C3 = New Class1
T = Timer
With C3
For i = 1 To LoopCount
Result = .Reflect(i)
Next i
End With
Print "explicit instancing + With: ", Format$((Timer - T) * 1000, "0.0msec")
DoEvents
End Sub
Olaf