Re: general performance question
Mike Schilling wrote:
There's this, which might not be what the OP had in mind:
LargeObject lg = new LargeObject();
// See discussion below
This has been discussed on this group, and the consensus is that the
method's stack frame continues to point to the LargeObject, so that it
can't be collected until the method returns. (It seems to me that the
JVM should be free to null out the reference once it goes out of
scope, or even if it's in scope but flow analysis makes it clear that
it can't be used any more, but that was a minority opinion.) Thus it
can make sense to replace the comment with
lg = null;
No, actually, it doesn't. This is one of the urban legends of Java.
I don't know of any "consensus" that the variable lingers through the method,
nor that it matters much if it does. The HotSpot compiler very well could
optimize an allocated object out of existence altogether, at runtime,
according to the runtime needs of the program. Variables and objects are
different, after all.
AFAIK it's not possible to guarantee the lifetime of an object will last past
its syntactic validity. There are all kinds of runtime conditions that could
have it vanish anytime after it's dereferenced or out of scope. Setting a
variable to null thinking that that will help release it really won't.
Brian Goetz is among the notables who have debunked the "set to null to help
Because allocation and garbage collection at one time imposed significant
performance costs on Java programs, many clever tricks were developed to
reduce these costs, such as object pooling and nulling.
Unfortunately, in many cases these techniques can do more harm than good
to your program's performance.
Sun warned of this risk and explained how explicit nulling was needed in
[certain] cases... . Unfortunately, programmers often take this advice
too far, using explicit nulling in the hope of helping the garbage collector.
But in most cases, it doesn't help the garbage collector at all, and in some
cases, it can actually hurt your program's performance.
Think of it this way - setting a variable to null has nothing to do with the
business logic of the program - it's a hack that is based on a superstition
relating entirely to implementation. Breaking the logic of your program in
order to imagine a performance improvement is a classic programming mistake.