Oscar kind said:
And unless the implementation of HashMap.clear() is extremely inefficient,
I believe it's cheaper to run HashMap.clear() than to cleanup the HashMap
objects with the garbage collector.
By what logic does "tramp through the entire HashMap setting things to
null, then let the garbage collector clean up" seem more efficient
than "let the garbage collector clean up"?
Trying to outguess the Java runtime environment is risky. Different
JVMs behave differently. That kind of "optimization" is something that
should be done only if you find that you need it, and only if you try
it both ways and see which way works better on YOUR JVM.
For most Sun JVMs, the most efficient practice is to discard objects
as soon as you no longer need them. This will keep them from having to
be copied into a survivor space, or worse yet, promoted to the tenured
generation. Allocating objects when you need them again is dirt-cheap.
One of the more recent articles discussing this can be found at
http://www-106.ibm.com/developerworks/library/j-jtp01274.html
Some quotes from that article:
"Sun estimates allocation costs at approximately ten machine
instructions."
"The JIT compiler can perform additional optimizations that can
reduce the cost of object allocation to zero."
"The cost of a minor garbage collection is proportional to the
number of LIVE objects in the young generation" (emphasis added)
"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."
"Walking the list takes CPU cycles and will have the effect of
visiting all those dead objects and pulling them into the cache --
work that the garbage collector might be able to avoid entirely,
because copying collectors do not visit dead objects at all."
"For most applications, explicit nulling, object pooling, and
explicit garbage collection will harm the throughput of your
application, not improve it"
"Before you muck up your program's design to improve its
performance, first make sure you HAVE a performance problem and that
following the advice will SOLVE that problem." (emphasis added)