Re: Optimizing Java method
Lothar Kimmeringer wrote:
private static WeakHashMap cache = new WeakHashMap();
cache.put(str, new WeakReference(res));
Usefulness of a cache built that way depends mostly on how the GC is
implemented. In general, it requires holding externally a strong
references to both, keys, and values. Otherwise, that cache may
reference a garbage only...
Better than that would be using a SoftReferences-based cache.
Unfortunately, there is no a SoftCache officially available in standard
Java distribution (however, the one undocumented named as such is
already there). Hopefully, we can build it ourself, or reuse already
written one, for example:
http://google-guice.googlecode.com/svn/trunk/src/com/google/inject/internal/ReferenceCache.java
A soft-cache useful here would be:
new ReferenceCache(SOFT, SOFT) { ...
Of course, as already said by Eric, before using a cache, you have to
proof yourself (by measurement), that it gives you any observable benefit.
piotr