What is the difference between Serializable - writeObject()/ReadObject and Externalizable - readExternal()/writeExternal() in Java?

前端 未结 1 1303
误落风尘
误落风尘 2020-12-19 08:10

I understood from this posting that Serializable is incredibly easy to implement, and resilient to change (in most cases all you have to do is update the serialversionUID).

相关标签:
1条回答
  • 2020-12-19 08:26

    You ask:

    why do we need to introduce the new interface Externalizable?

    The best rationale I've been able to find (in Oracle documentation) is in the WebLogic JMS Best Practice document:

    "The CPU cost of serializing Java objects can be significant. This expense, in turn, affects JMS Object messages. You can offset this cost, to some extent, by having application objects implement java.io.Externalizable, but there still will be significant overhead in marshalling the class descriptor. To avoid the cost of having to write the class descriptors of additional objects embedded in an Object message, have these objects implement Externalizable, and call readExternal and writeExternal on them directly. For example, call obj.writeExternal(stream) rather than stream.writeObject(obj). Using Bytes and Stream messages is generally a preferred practice."

    In short, you can get better performance using Externalizable, at least in some situations.

    And "the difference" is that if you use Serializable the work of serialization is typically done for you, but with Externalizable you need to code it yourself.

    0 讨论(0)
提交回复
热议问题