I'm wondering if I can depend on the .NET garbage collector to avoid keeping a bunch of extra heap objects around in this type of scenario:
public static void Main(string[] args) {
var a = ParseFileAndProduceABigTreeObject(args[0]);
var b = WalkTheBigTreeObjectAndProduceSomeOtherBigObject(a);
var c = AThirdRoundOfProcessing(b);
Console.WriteLine(c.ToString());
}
In each phase here, it's to be understood that the objects returned by each method hold no references to the previous objects, so b
doesn't reference a
, and c
doesn't reference a
or b
.
A naive implementation of GC would keep a
around for the entire duration of the program because it continues to be reachable via the Main
method's stack frame.
What I'm wondering is if I can depend on .NET to do liveness analysis and determine that by the time the third line (AThirdRoundOfProcessing
) is executed, a
is no longer needed and its memory can be reclaimed if necessary?
I'm almost certain that .NET handles cases like this at least sometimes, so my question is really this: is it consistent enough for me to rely on it, or should I just assume that it might not and take measures to make the code more foolproof? (Here, for example, I could set a
to null
.)
P.S.: What about OpenJDK, would it handle it nicely?
Edit: I may not have been clear. I'm aware that, in terms of standards, the runtime is allowed but not required to collect a
. Were I running my code on an imaginary runtime where all I knew was that it's conformant, I'd have to live with that uncertainty. However, my code is running on a recent version of the Microsoft .NET 4 runtime. What I'd like to know is whether that runtime can be expected to do this or not. The runtime is actual code and it's possible to know exactly what it would do. Maybe someone out there has that knowledge and would like to share it.