I have a class representing a set of values that will be used as a key in maps.
This class is immutable and I want to make it a singleton for every distinct set of values, using the static factory pattern. The goal is to prevent identical objects from being created many (100+) times and to optimize the equals method.
I am looking for the best way to cache and reuse previous instances of this class. The first thing that pops to mind is a simple hashmap, but are there alternatives?
There are two situations:
enum
EnumMap
is optimized for it Depending on the usage pattern, you may choose to only cache, say, the last N instances, instead of all instances created so far. This is the approach used in eg re.compile
in Python's regular expression module. If N is small enough (eg 5), then a simple array with a linear search may also work just fine.
For Map
based solution, perhaps a useful implementation is java.util.LinkedHashMap
, which allows you to enforce LRU-like policies if you @Override
the removeEldestEntry
.
There is also LRUMap
from Apache Commons Collections that implement this policy more directly.
enums
MapMaker
, soft keys and values, etc What you're trying to make sounds like an example of the Flyweight Pattern , so looking for references to that might help clarify your thinking.
Storing them in a map of some sort is indeed a common implementation.
What do your objects look like? If your objects are fairly simple I think you should consider not caching them - object creation is usually quite fast. I think you should evaluate whether the possibly small performance boost is worth the added complexity and effort of a cache.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.