Mario said:
What's more efficient from a performance/garbage collection point of
view - assigning an object to a variable or not?
Eg:
public class Test {
public void method1() {
Employees e = new Employees();
List l = e.getNames();
}
public void method2() {
List l = (new Employees).getNames();
}
}
In this simple example there will probably be no discernible
difference -- certainly no different worth worrying about. In
method2 the Employees object may become collectible about 1.642
nanoquivers sooner than in method1, but you'll never notice it.
In order to see (or have a chance of seeing) any difference
you need something like
void method3() {
Employees e = new Employees();
List l = e.getNames();
someCalculationThatTakesLotsOfTime();
}
Here, the Employees object remains uncollectible as long as `e'
survives, so if it isn't needed during someCalculation... you
are "wasting" memory for that period of time. However, even
this isn't likely to make much trouble unless someCalculation...
really does take LotsOfTime *and* an Employees object (and any
other objects it "owns") take up a lot of memory. *If* both of
these are true, you may get some benefit from the method2 way
of doing things, or by writing `e = null;' once you're through
with the object.
IMHO, people worry about this more than is needful. That's
not to say there isn't a potential problem, just that the problem
isn't as prevalent as fear makes it seem. Do you check for
cobras under your bed every night?