[Mono-dev] Why does .NET object lifetime not extend into an instance method call?

David Jeske davidj at gmail.com
Sat Aug 25 04:27:31 UTC 2012

On Fri, Aug 24, 2012 at 8:31 PM, Jonathan Pryor <jonpryor at vt.edu> wrote:

> > I'm sorry for my naivety. Why does allowing unused function arguments to
> be collected before a function returns have such important effects on
> memory usage?
> Java. :-)
> The context is the JVM, and "large" methods. Many JVM implementations used
> to do as you suggested, and wouldn't collect a variable until the method
> referencing the variable returned. This even applied to local variables!
> Instead of having "precise lifetime" semantics (as determined by the
> instruction pointer), it only cared about stack frames.
> The result of this behavior is that developers would write "huge" methods
> which allocated "lots" of objects, all of which would be considered "live"
> even when a local was no longer being used. Thus came a body of guidelines
> that you should null out instance/local variables so that the GC could
> actually collect intra-method garbage:
>         http://stackoverflow.com/questions/473685
>         http://stackoverflow.com/a/503714/83444
> Needing to null out a local variable is, of course, insane -- "why can't
> the GC figure this out!" -- so .NET (and modern JVMs!) now precisely track
> which variables are in-scope and out-of-scope, and will allow collection of
> any-and-all out-of-scope variables even within the method.

Thanks for that detailed description.

I don't still don't see why function arguments are handled as aggressively
as local variables. One could argue that the contract of a function call
implies that the arguments are "referenced" by the caller until after the
call is completed... For example, expect that in "new Foo().Bar();", Foo is
not eligible for collection until after Bar returns.

However, at least I now understand why this idosyancracy exists. Thanks
very much!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-devel-list/attachments/20120824/b4f4cc5f/attachment.html>

More information about the Mono-devel-list mailing list