Jeff Verdegan wrote:The tradeoff between an unneeded lookup and an unneeded object creation may be a bit of premature optimization in either direction, but I'll usually go with the first case (extra lookup).
Yeah, I guess if it's a cache, the first style might save you creating a lot of empty Lists (or V's) unnecessarily.
First thing I'd ask is why are you implementing a cache? There are lots of existing implementations that are free, open source, debugged, documented, etc.
So if you want to learn, lets keep going. But if you just want to use one, I'd start with the Google Guava com.google.common.cache.* classes.
Once you get the fundamentals working, you really need to thing long and hard about what strategies you want to use, when do you kick entries out of the cache, how often do you kick one or more out, what is the loading strategy, etc.
The initial discussion of them usually start with a last used goes out first strategy, but that is not optimal in many real world usages.