Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Do more references to one variable cost more memory?

Tags:

java

memory

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?

like image 895
Ushwald Avatar asked Mar 30 '14 16:03

Ushwald


People also ask

Do references take up memory Java?

As has been mentioned, it will use either 32-bits or 64-bits, however if the reference is only placed in a register, it might not use any memory.

Can multiple variables reference the same object in memory?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.

How much memory does a reference take in Java?

References have a typical size of 4 bytes on 32-bit platforms and on 64-bits platforms with heap boundary less than 32Gb (-Xmx32G), and 8 bytes for this boundary above 32Gb. This means that a 64-bit JVM usually requires 30-50% more heap space.

How many bytes of memory are required by a reference to an object in Java on a typical 64-bit machine?

In a 64-bit system, object references are typically 8-byte long.


2 Answers

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.

like image 145
Hannes Avatar answered Oct 20 '22 18:10

Hannes


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

like image 43
Lesto Avatar answered Oct 20 '22 19:10

Lesto