Home > DeveloperSection > Forums > Do null properties of Java objects use memory?
Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    July-20-2015 7:13 AM

 Java Java 
Ratings:


 1 Reply(s)
 465  View(s)
Rate this:
I am connecting to a webservice that sends down many different JSON objects. Rather than use a Java JSONObject I plan to use the GSON library to convert to POJOs. Rather than a huge amount of classes (one for each of the possible JSON service responses), I want to have a generic java object that can hold all possibilities:

public class GenericJSONResponse{
    public long objectKey;
    public GenericJSONResponse subObject1;
    public String description;
    // ...
}
I think this is a good aproach since the properties that get sent down by the server vary greatly. All server responses will only include a subset of the possible GenericJSONResponse properties. Will the properties that do not get populated take up memory even if they are null? My generic object will have many properties that are not used and I don't want them taking up precious memory.


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    July-20-2015 9:04 AM

Each field (of reference type) in a class occupies a pointer-sized (32-bit or 64-bit) chunk of memory per instance of the class.

This memory is used to store a reference to the value of the field, which may be a reference to an existing object or a null reference.

If you don't initialize your references then only the amount of memory required for storing the reference will be used.

If you create a new object and assign it to the reference then memory for new object will also be used and the memory required for reference will be used.

If you simply assign an existing object to an existing reference no new memory allocation is required.

Null is just a value that a reference can have. It is 4 bytes on 32-bit systems or 8 bytes on 64-bit systems


Don't want to miss updates? Please click the below button!

Follow MindStick