Re: Java Memory question
On 03/14/2011 05:37 PM, Joshua Cranmer wrote:
On 03/14/2011 05:01 PM, Eric wrote:
1. I admit putting declarations at the instance level instead of the
methods was partly for neatness, for maintainability, to look in one
place and see what kind of variables are used. The other reasoning
was performance, thinking if it's only used in one method but the
method may be called many times it would slow it down to recreate it
each time.
All modern JVMs are tuned under the assumption that most objects don't live
all that long, so you actually tend to get better performance by keeping
variables minimally scoped. Object pooling in particular will nearly always
degrade your performance, and should only be used if you *really* know what
you are doing.
The type of reasoning that re-use will speed things up is called "premature
optimization". This is a technical term that refers denotatively to attempts
to optimize code prior to having evidence of need or that the proposed
strategy will benefit performance (however /that/ is defined!). Connotatively
it refers to doing things that actually harm performance (however /that/ is
defined!) out of ignorance of the way things actually work, as here.
It is best to code for correctness and good algorithms, scoping variables to
their actual need, than to delude oneself with fantasies of micro-improvements
in performance.
Brian Goetz addresses some of these matters at the IBM Developerworks site.
<http://www.ibm.com/developerworks/java/library/j-jtp04223.html?ca=dgr-lnxw01JavaUrbanLegends>
<http://www.ibm.com/developerworks/java/library/j-jtp10283/>
<http://www.ibm.com/developerworks/library/j-jtp01274.html>
<http://www.ibm.com/developerworks/java/library/j-jtp09275.html>
--
Lew
Honi soit qui mal y pense.