开发者

Object initialization in a method

开发者 https://www.devze.com 2023-01-07 13:32 出处:网络
Is there a difference from POV Performance / MemoryUsage initializing a object before, or after a return condition, like in the \"sample\":

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


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();


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消