1
votes

I have a problem where i need to store key, value1(float) and value2 (very long string) in a map, where value1 is available for every key and value2 is available only for 1% of the keys.

I can think of 2 possible solution

  1. two maps like map1 = map(key1 ,map(key2, value1)) and map2 = map(key1, map(key2,value2)) pros - no unnecessary reference variables. cons - storing the same key twice wasting memory there.

  2. use one map with a custom object value. map1 = map customobj{float value1; string value2} pros - no duplication of key. cons- 99% of the customobj will have value2=null and hence will consume memory for reference pointer.

Basically my ultimate question is does unused references (in customobj) consume memory or would compiler optimize it ? i am leaning towards soln 2, as i dont want to waste memory by storing the same key1 and key2 twice. On the other hand 99% of the time value2=null, which makes me wonder whether soln1 is better.

I am using Java and I would like to hear some advice.

EDIT: I didnt realize that SO didnt print the map structure i posted, i edited that . both key1 and key2 are string (mostly fixed length id string)

2
Premature optimization? A reference is tiny. - Sotirios Delimanolis
I like solution 2. References are cheap. Unless you have hundreds of millions of them, they're just not going to matter as much as the simplicity of the second solution. - Ian McLaird
key is fixed size string. see my edit above - srini
how about a custom class with char[] and , private String readValue() - Srinath Ganesh

2 Answers

2
votes

I would choose solution depending on the key size and type

Solution 1 is --

1) HashMap with key and value1(float)

2) HashMap with key and value2(string)

This would only need extra space for 1% of keys. If the key size is huge, then I would go with solution 2.

Solution 2 is --

Single HashMap with a custom object. Create a custom object using structure or class.

Though memory of references is very small, each object still occupies constant memory of object overhead(16 bytes) and padding(4 bytes). A HashMap key from solution 1 will probably occupy around 8 bytes overhead for each key-value pair. So choose solution 2 if your key size is bigger than a integer or character.

0
votes

Solution #3. HashMap where value is either Float or CustomObj{float value1; String value2}. Do instanceof at runtime to find out which one is which.

That, assuming optimization is even an issue. Premature optimization is the root of all evil, right? If you are not sure you NEED to optimize just yet, then just code in the way you conceptualize the real world you are modeling.