代码之家  ›  专栏  ›  技术社区  ›  serhio

方法中的对象初始化

  •  2
  • serhio  · 技术社区  · 15 年前

    与POV Performance/MemoryUsage在返回条件之前或之后初始化对象有什么区别吗,如“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
    
    3 回复  |  直到 15 年前
        1
  •  2
  •   Marc Gravell    15 年前

    如果你的意思是,但是比较:

     Dim obj as New ComplexObject()
    

    之前 If condition Then Return Nothing new 每次一个对象,即使它很快被丢弃并从gen-0收集(对于 Nothing 声明 它(没有 New If ,则两者应该相同(局部变量的位置不相关,因为IL中的所有局部变量都是方法范围的)。

    return condition ? null : new ComplexObject();
    
        2
  •  1
  •   Will A    15 年前

    唯一的区别是,在不返回任何内容之前创建对象将占用更多的CPU—无论哪种方式,当对象不再被引用时,都将正确地对其进行垃圾收集。

        3
  •  1
  •   Darin Dimitrov    15 年前

    是的,当您分配一个本地对象,一旦它离开方法,它就需要被垃圾收集,这是有区别的。

    推荐文章