Skip to content
Advertisement

Why is deserialized object’s size different from serialized object’s size?

I’m saving some Java objects in files. I seralize them that way :

Class Timestamp.java:

JavaScript

Class ObjId.java:

JavaScript

CachedObj.java :

JavaScript

The rest of my code :

JavaScript

In another place in my code I deserialize that way :

JavaScript

And I have a function that calculates an CachedObj object size :

JavaScript

My question is, when I run the following code :

JavaScript

Why are size1 and size2 different ? How can I get the size of obj2 such as I’ll get the same value of size1 ?

Advertisement

Answer

This isn’t a complete answer. Your issue with slight change in the serialised size is down to the SimpleDateFormat in Timestamp. Comment out the instanceFormat field, or make the field transient will make all the sizes the same again, or change your example to just serialise SimpleDateFormat instead of CachedObj:

JavaScript

SimpleDateFormat isn’t a good type of field to add to the serialized format of your class as it has a relatively big memory footprint (~ 48KB!). It would be better to created one instance in the application code, never serialised, and re-use it in same thread for all your Timestamp <-> String conversions performed rather than allocate new instance per Timestamp.

If you are performing a significant number of conversions re-using the same SimpleDateFormat for date to string formatting will reduce overall memory churn on large application servers.

By the way, your calls can be simplified with try-with-resources any adapted for use by and Serializable:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement