views:

583

answers:

5

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?

+4  A: 

No, null is also information and has also to be stored.

Toad
+7  A: 

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?

Pete Kirkham
Yeah, good question. :) So a field is equivalent to a C pointer (which requires memory for itself, too)?
Hanno Fietz
Yes, variables of reference types (classes) are references to objects on the heap, equivalent to C pointers. Memory would be taken up for the pointer and for the object it points to. Primitive types, such as int are stored directly and always are the same size.
Joe
A: 

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

Kage
Those are not stored per-instance.
CPerkins
True. The original question was about the objects' space costs. Thanks :-).
Kage
+1  A: 

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

MyClass {
    public Object obj;
    MyClass(Object o) { obj = o; }
}

MyClass a = new MyClass( new HashMap() );
MyClass b = new MyClass( null );

the two objects a and b themselves take up the same amount of memory (they both hold one reference), but the Object obj referred to by a takes up memory on the heap, so this memory could have been saved by setting the reference to null.

Bill the Lizard
+1  A: 

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 to null.

Jesper