Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute fields vs. attribute-value map

I have a (java) class with about 10 attributes, many of them potentially staying uninitialized and are not accessed during lifetime of an object.

Therefore I'm considering using a Map<String,Object> as an attribute-name -> attribute-value map instead of a lot of fields, in order to save resources.
Now I am wondering, if there exist any offical or unofficial rules, when and how to decide on one of the described possibilities. How many attributes should a class have, before I should consider using such a map? Should I use it at all?

Thanks in advance for your advice/opinions on that.

like image 925
Daniel K Avatar asked Mar 08 '12 16:03

Daniel K


2 Answers

Okay so you're doing this to save memory I assume because clearly you're not saving CPU resources by accessing a map instead of a field. So let's see how good that works out: (assuming 64bit JVM without compressed oops - which is unrealistically but shouldn't change the results too much, you can compute it yourself easily)

Basically a field in java will never take up more than 8bytes (well word size for references). So this means for your class with 10 fields, assuming all are unused the best we can save are 8*10 bytes = 80byte.

Now you want to replace this with one HashMap instead - that means we already use up 8 extra bytes for that. Also the HashMap is always initialized so we get the overhead of: 2 words header + reference + 3 ints + float + 1 array (2 words overhead, 4byte size, 16 references by default) which takes up 182 bytes of memory.

May I congratulate you to saving a whopping -110 bytes!

PS: I think the smallest possible default value for the backing array of the hashset is 2, so you could use that and come out about even. But as soon as you store objects in the set, you get additional overhead from the Wrapper objects used by the class. So really it's a bad idea.

like image 90
Voo Avatar answered Sep 22 '22 08:09

Voo


It's not about how many different attributes you have it's about how they are used and what is needed. A Map will allow for more flexibility to not have attributes or to have different attributes for different instances or add attributes later (through adding things to the Map). But if the attributes are different types String, Integer, Doubles etc this will require making the Map of type Object and casting all the values when you use them (a lot more work for you).

like image 32
twain249 Avatar answered Sep 24 '22 08:09

twain249