For simplicity’s sake, let’s say I have two instances of HashMap<String, String> where they share the same keys. What I want to know is there a performance and memory difference between that and representing those two String values in an Object and storing them in HashMap<String, Object>.
My actual problem uses an instance of HashMap<String, HashSet<String>> and two instances of HashMap<String, Double> and I was hoping that by consolidating them, I’d save memory somehow, but I wasn’t sure if there’d be a performance impact from using self-defined Object versus a native object like HashSet or Double as values.
The hashes are calculated from the strings, so there won’t be a speed impact. The space impact (a very slight increase) will be negligible in the long run. If it makes the code more legible, do it and screw the performance (as long as we’re not talking huge performance bottlenecks, it doesn’t matter).
Speed
For the speed impact, remember that in a
HashMap<String, ?>, theStringis what gets hashed. You may see a small increase in speed, actually, since you’ll only have to do one lookup to find your custom object compared to 3 lookups.Space
For space impact, remember that
HashMapuses an inner array that’s the size of a power of 2. If you’re using just a vanillaHashMapwith no special settings like a custom load factor, then you may see a slight space increase because right now you have (roughly, of course, this is just simplified):And after combining it, you’ll have
This is ignoring constant-size information that doesn’t grow with the map. Objects take up more space than just the references to their fields, but not very much.
Legibility
The custom object option wins this one hands-down. It’s way cleaner and is very OOP, fitting into Java very, very well. Regardless of the performance, you should do this anyway. It’ll look better in the long run and be more maintainable.
For example, if you wanted to add fields to the custom object, that’s easy. But having the separate maps means creating more maps for more variables, which is dirty. I say go the OOP way.