Tech Off Post

Single Post Permalink

View Thread: is 'new object().property' or 'new object().method()' a good idea?
  • User profile image
    Curt Nichols

    Pop Catalin Sever wrote:
    1) if LongRunningMethod() acceses fields on MyObject instance the "this" parameter is passed on the stack to the method meaning you have a rooted reference to the object instance, the method call practicaly is like this

    newobj MyObject //Returns a reference in the stack
    call
    LongRunningMethod



    What you're not seeing is that the JITter helps the GC know when the reference is no longer needed. In this case the MyObject reference is needed only to invoke the call to LongRunningMethod, but isn't needed afterward. If a GC occurs during LongRunningMethod the instance may be collected if there are no other rooted references to the object.

    See here if you want code to reproduce the behavior.