tags:

views:

22

answers:

3

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
+1  A: 

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.

Will A
So, you confirm that 'A' variant is more CPU and memory consuming.
serhio
I would certainly expect it to be - it's possible that the compiler would 'do the right thing' and move the object creation past the if(...) return, for an optimized release build, but I wouldn't bank on this being the case.
Will A
+1  A: 

Yes there's a difference as you are allocating a local object that once it leaves the method it needs to be garbage collected.

Darin Dimitrov
So, the compiler will NOT create all declared object at the beginning of the function, regardless of the declared position?
serhio
It is possible that in `Release mode the compiler detects that you are creating an object that is never used so it is possible that it removes it, but I wouldn't rely on it. Simply declare/initialize variables only when needed and as late as possible.
Darin Dimitrov
@Darin: In fact, I think at the compile time the 'condition' can't be verified, only in Runtime this is possible.
serhio
+2  A: 

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();
Marc Gravell
I was afraid that the compiler anyway creates(and initializes) all the declared (outside of internal cycles) objects.
serhio
A propos, the `?` in C# or `IIF` operator in VB.NET can't be used in my situation, because OR I return a Nothing(null) OR I need to do some stuff with the new ComplexObject, not just directly return it.
serhio
@serhio - the *declaration* happens at the start of the IL; however, the creation **must** happen at the same logical point as your code says it does.
Marc Gravell
@Marc: Okey... I note the difference between *declaration* and *creation* ...
serhio