Is it correct to assume a Java object only takes up the 8 bytes for the object reference as long as all it's members are set to null
or does the definition of members already use up space in the instance for some reason?
In other words, if I have a large collection of objects that I want to be space efficient, can I count on leaving unused members set to null
for reducing memory footprint?
The Java Language Specification and the Java Virtual Machine Specification do not say anything about the size of Java objects in memory - it is deliberately left undefined, because it depends on the implementation of the JVM. This means that you cannot make any assumptions on how much memory a Java object uses in general or what the memory layout of a Java object in memory is.
As others have already said: A reference (variable) takes up memory, whether the reference is
null
or not. Your objects will not shrink and take up less memory when you set member variables tonull
.The object references themselves will still take up some memory, so the only real memory savings will be from the heap objects that would have been referred to.
So, if you have
the two objects
a
andb
themselves take up the same amount of memory (they both hold one reference), but the Objectobj
referred to bya
takes up memory on the heap, so this memory could have been saved by setting the reference to null.No, null is also information and has also to be stored.
When a Java object has all its members are null then to it will consume memory because It also has some additional memory requirement for headers, referencing and housekeeping.
The heap memory used by a Java object includes
memory for primitive fields, according to their size.
memory for reference fields (4 bytes each).
an object header, consisting of a few bytes of "housekeeping" information.
Objects in java also requires some "housekeeping" information, such as recording an object's class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc.
Java object header size varies on 32 and 64 bit jvm.
Although these are the main memory consumers jvm also requires additional fields sometimes like for alignment of the code e.t.c.
So this is the reason when your Java object has all its members are null then to it will consume memory.
No, you need either 4 or 8 bytes ( depending whether it's a 32 or 64 bit system ) for each null you are storing in a field. How would the object know its field was null if there wasn't something stored somewhere to tell it so?
What about class, object and method names? As you can call, access or instantiate them using Java reflect, the names have to be stored somewhere too, right? But CMIIW.
Kage