Do Hashmaps optimize memory if values are duplicated?
Example:
Say I want to create a Hashmap with 26 keys which will be 'A'
through 'Z'
for this example. Now let's say that I want keys 'A'
, 'M'
, and 'Z'
to r开发者_StackOverflow社区eturn the same integer value of 123
. When this map is created, does the map get optimized such that only one value is stored in memory? Or does it still treat this as 3 different keys with 3 different values, even though the 3 values are the same.
I hope that question makes sense.
Thanks
In short, no.
Some classes may cache similar variables under certain circumstances, but the HashMap itself will not.
Now, with integers, if you acquire your integers with Integer myInt = Integer.valueOf(123)
then it will always return the same Integer
reference, but that's just because of the mechanics of Integer.valueOf()
having a cache of the closest 256 Integers
to 0. You can not and should not rely on this mechanism for memory efficiency.
If you have the following, you can make some assumptions:
Map<String,Integer> map = new HashMap<String,Integer>();
Integer myInt = new Integer(123); // one Integer object
// add it 3 times
map.put("A",myInt);
map.put("M",myInt);
map.put("Z",myInt);
You can assume that:
There are 3 references (like pointers) to Integers in the Map, and they take up some memory. There is 1 Integer object that also takes up memory.
A HashMap
does not in any way try to save space by "reusing" the value elements (that would require it to compare each added value to all the existing ones, which would be very expensive - after all, it is only the keys that are hashed for quick lookup). However, Java itself keeps a small internal cache of small Integer
values, which I believe is used when autoboxing. So in this particular case, if you call yourHashMap.add(42)
twice, the hashmap will actually contain two references to the same Integer
instance with the value 42.
精彩评论