I have a specific usage of HashMap
, where it just stores few entries (usually less then 5-10) for String
keys. I just have to add entries, get them by key, and sometimes to iterate the entry set. Entries are never removed during the lifespan of the map. I have some operation where 5-6 such smaller maps are needed and allocated every time during single user usage, i.e. request.
I am using HashMap
for this. However, I wonder if there is a better, optimized implementation of Map-alike structure that I might use for this? For example, one that would allocate less space and that might be faster for small number of elements. Or HashMap
is simply good enough?
Note that I don't insist to follow Map
interface for this.
My thoughts are going into direction of array-backed map, something like this implementation that caught my attention from JetBrains: SmartFMap (An immutable map optimized for storing few entries with relatively rare updates, as they say).
Does anyone know about such alternative implementations that would be a good HashMap
replacement?
ADDON
My initial idea is what @Evgeniy Dorofeev said in his answer, to have sorted array of entries and use binary search, but with following modification. Since I need to add elements to this collection and to prevent re-creation of array I was thinking of using array with some empty spaces. First element is added eg in the middle of the array, second element is added in the middle of remaining half (below or under, depending on sorting order). If initial size of such array is good, we can (mostly) prevent recreation of this array and still be able to binary/radix search.