Is there a penalty to add
implements Serializable
to a Java class? Impact on size of instantiated object or performance?
The Student would not be Serializable, and it will act like a normal class. Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link.
If our class does not implement Serializable interface, or if it is having a reference to a non- Serializable class, then the JVM will throw NotSerializableException . All transient and static fields do not get serialized.
If a super class implements Serializable, then its sub classes do automatically. When an instance of a serializable class is deserialized, the constructor doesn't run. If a super class doesn't implement Serializable, then when a subclass object is deserialized, the super class constructor will run.
If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.
There is no performance impact unless you perform serialization/deserialization but there are trade offs in terms of api design.
From Effective java by Joshua Bloch
- A major cost of implementing Serializable is that it decreases the flexibility to change a class’s implementation once it has been released
- A second cost of implementing Serializable is that it increases the likelihood of bugs and security holes
- A third cost of implementing Serializable is that it increases the testing burden associated with releasing a new version of a class
Upto what extent these are applicable to you depend of your usecase.
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