Re: garbage collector
Lew wrote:
Doesn't it force the object into the tenured generation, actually
hurting memory usage?
Joshua Cranmer wrote:
But the object is only being created once rather than one million times.
I suppose it is ultimately slightly worse on the memory usage, but the
garbage collection procedure will be triggered fewer times. Inside the
loop, it is likely to have a slight increase on memory--there are fewer
uncollected fragments on the heap--but it will properly degrade memory
somewhat outside of the loop (expanded scope, etc.). [*]
It's that "expanded scope" that worries me. You have to make sure that the
Date instance is properly cleared between instances, for example, perhaps as
part of reinitialization. You now have a variable visible outside its
intended range, which in some applications can become an issue. Memory
allocation in Java is blindingly fast, and young-generation GCs don't take all
that long.
Another consideration is that long-lived mutable objects present threading
challenges. Alas, Date is not immutable, but if one had a better example than
Date one might find the benefits of an immutable object outweigh the downside
of reinstantiation inside the loop, in the face of multi-threaded considerations.
I'm not making the case that having the variable inside the loop will be
faster, only that it is not a sure thing that all types will benefit from
re-use of an instance in lieu of re-allocation. There are many scenarios
where the overhead of managing a long-lived, wide-scoped mutable object will
be worse than the overhead of newly instantiating a short-lived, limited-scope
immutable object.
--
Lew