Does serialization in Java always have to shrink the memory that is used to hold an object structure? Or is it likely that serialization will have higher costs?
In other words: Is serialization a tool to shrink the memory footprint of object structures in Java?
Edit
I'm totally aware of what serialization was intended for. But you know, tools can be misused. My question is, whether it is a good tool to decrease the memory usage.
So what reasons can you imagine, why memory usage should increase/decrease? What will happen in most cases?
Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.
In some cases, the secondary intention of data serialization is to minimize the data's size which then reduces disk space or bandwidth requirements.
Serialization is the process of converting a data object—a combination of code and data represented within a region of data storage—into a series of bytes that saves the state of the object in an easily transmittable form.
No... serialization is a way to write or read a representation of an object's state as a byte array. It is not an alternative in-memory representation. An object's serialized form may or may not consume more bytes than it does inside the JVM; typically it would be quite comparable. In rare cases it could be more, and sometimes an object's state can be completely serialized in a way that consumes fewer bytes than it does on the heap. But no to answer the question it is not a "tool to shrink memory footprint".
My question is, whether it is a good tool to decrease the memory usage.
No it is not a good tool for doing that. The serialized object representation includes a lot of 'metadata' that describes the type and representation of the object. Unless you serialize a significant number of objects into one 'stream', the 'metadata' overhead will make the serialized form larger than the original form. Ignoring this overhead, the serialized representation is typically more compact, but the saving will depend to a considerable extent on the object's representation types. (Take a look at the "Object Serialization Stream Protocol" for more details.)
And as other answers mention, you temporarily increase memory usage while serializing and deserializing because you have to hold both the serial and object representations AND the map used for dealing with cycles, etc.
If you want to represent a data structure in a compact form in memory, you would be better off developing your own application-specific serialization scheme. But IMO, it would be better still to write the data to the file system or a database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With