Reputation: 28596
Is there a difference from POV Performance / MemoryUsage initializing a object before, or after a return condition, like in the "sample":
Function Foo() as ComplexObject
' is there a difference ??? '
' A '
' Dim obj as New ComplexObject() '
If condition Then Return Nothing
' is there a difference ??? '
' B '
Dim obj as New ComplexObject()
...
Return obj
End Function
Upvotes: 2
Views: 75
Reputation: 1064324
If you mean, but comparison to:
Dim obj as New ComplexObject()
before the If condition Then Return Nothing
, then yes: there is a difference: it done before, then it will new
an object each time, even if it is quickly discarded and collected from gen-0 (for the case when Nothing
is returned). However, if you just declare it (without New
) before the If
, then the two should be identical (the position of the local variable is irrelevant, since all locals in IL are method-wide).
I don't know the VB, but in C# you could also use a conditional operator:
return condition ? null : new ComplexObject();
Upvotes: 2
Reputation: 1039598
Yes there's a difference as you are allocating a local object that once it leaves the method it needs to be garbage collected.
Upvotes: 1
Reputation: 25018
The only difference is that creating the object prior to returning Nothing will use an amount more CPU - either way the object will be correctly garbage collected as and when it's no longer referenced.
I'm all in favour of defining/declaring variables as late as possible.
Upvotes: 1