Is there a penalty to add
implements Serializable
to a Java class? Impact on size of instantiated object or performance?
Is there a penalty to add
implements Serializable
to a Java class? Impact on size of instantiated object or performance?
The cost is close to zero, not worth being concerned about.
Some further details:
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.
Serializable
you can't do that at all so there is nothing to compare it with. –
Porche The cost is close to zero, not worth being concerned about.
Some further details:
Unless you / someone else actually serializes / deserializes, there won't be any impact. Serializable
is just a marker interface.
It probably will only increase the size of the generated bytecode by a few bytes.
You should always consider the maintenance overhead first. The cost of a deployed application over its live can be several times the cost of developing it.
In this case, the cost of making a class Serializable, but not actually used for Serialization could cause bugs or confusion far grater than the performance cost. e.g. say it takes 1 minute or someone's time to determine the Serializable is not needed, this can cost far more than the few nano-second extra startup time the application incurs.
If you actually need it to be Serializable, you can't compare it to the non-Serializable version because only the first case will actually do the job required.
Serializable
is just a "marker" interface. It does not require you to implement any methods.
The only thing is that it is recommended to have a static final long serialVersionUID
to help the serialization API. That costs a single long
value per serialized class.
You might want to check out this article about Java Serialization API. It describes most of the caveats of serialization / deserialization in detail.
© 2022 - 2024 — McMap. All rights reserved.