Re: memory management
Roedy Green wrote:
On Wed, 31 Oct 2007 09:14:12 -0400, Lew <lew@lewscanon.com> wrote,
quoted or indirectly quoted someone who said :
It is also usually better to allocate new objects in the loop than to hang on
to one for multiple iterations.
Why is that?
On account of the garbage collector is optimized for short-lived objects, and
making long-lived ones risks having inter-generational references. In
addition, the optimizer is able to optimize away the object allocation
altogether in many cases. The cost of short-time object memory allocation and
GC is much less than most people suppose.
I have been reading article after article explaining this and recommending
that holding on to objects is not always helpful, and can even be harmful.
Also, extending an object's life artificially widens the scope of the
variable, which is against good code engineering maxims.
Naturally there are situations where it's better to keep an object than
reallocate, but the use of widened object scope to "optimize" turns out to be
an antipattern.
Articles that shed some light on this and related topics:
<http://www.ibm.com/developerworks/java/library/j-jtp01274.html?S_TACT=105AGX02&S_CMP=EDU>
<http://www.ibm.com/developerworks/java/library/j-jtp09275.html>
<http://www.ibm.com/developerworks/java/library/j-jtp04223.html>
--
Lew