6

What I really want to know is: say I would create a class called "Family" in Java, and each family would have a number of "familyMembers" as member variables, would it cost any more memory to also declare for each of the "familyMembers" what "Family" they are part of? in other words, say the family Smith has 3 members, Dad, Mom and Kid, would it cost any more memory to make Family "Smith" a member variable of each familyMember: Dad, Mom and Kid?

Ushwald
  • 73
  • 1
  • 8

3 Answers3

2

unless you use the new keyword or primitive type, you only use memory needed to store the reference

Lesto
  • 2,260
  • 2
  • 19
  • 26
  • 1
    Don't forget about primitives! – Tyler Mar 30 '14 at 16:46
  • okay so every reference costs a bit of memory? Does that mean that adding more family members, and therefore more references to the "Smith" Family, would cost more memory? – Ushwald Mar 30 '14 at 16:49
  • 1
    @Ushwald: Every sandwich costs 5 dollars. Does that mean that buying more sandwiches would cost more money? – JB Nizet Mar 30 '14 at 16:51
  • yes, but I'm not talking about declaring more variables here, I'm talking about referring to the same variable in more than one way – Ushwald Mar 30 '14 at 16:54
  • 2
    You don't refer to a variable. You refer to an object. Each time you have a reference to an object, the reference needs to store the address of the object. And that costs 4 bytes of memory. – JB Nizet Mar 30 '14 at 17:00
2

Everything costs something. If adding another class variable, it will cost in two ways. First some bytes for your declaration in the class when it is loaded and then for each reference another 4 bytes. This is because you class definition must be loaded into memory (permanent, permgen space) and because every reference is unique on your stack the 4 bytes per reference.

Hannes
  • 2,018
  • 25
  • 32
0

Yes, the reference to the family, when stored in a family member, increases the instance size of a family member by the size of a reference.

Note that in practice this does not necessarily mean more memory consumption because of various memory management techniques Java VMs use.

Ozan
  • 4,345
  • 2
  • 23
  • 35