Re: Java Memory question
On 3/23/2011 12:23 PM, Eric wrote:
....
The relevance is, getting back to the original question, how much does
a program want to keep in memory? Is it more efficient to create an
object and reuse it or to recreate the object as needed? ...
This question depends on so many things that the only way to answer it
accurately is by measuring the specific case.
You need the baseline version that just does things as simply as
possible anyway, so I would start by writing and testing that. Once it
is working, measure where the time is going. Consider object reuse if
you have done that and found that a constructor is a heavy hitter in the
profile. After doing the changes, compare to the baseline to make sure
the changes are bringing real benefit.
I have generally not found construction to be much of an issue in my
programs. Even if a constructor were a heavy hitter, you will only be
able to gain by re-use if there is something really slow being done in
the constructor that you can skip in the recycling code.
There is one concession to constructor-related issues that I am tending
to make in classes whose interfaces will be difficult change later: Use
a static factory method rather than a public constructor. That way, you
can change how new objects are obtained without changing the callers.
Patricia