问题描述
据说Java的默认序列化机制效率不高,因为a)它发现通过反射写入/读取的字段通常很慢b)它将额外的数据写入流。
It's said that Java's default serialization mechanism is not very efficient because a)it discovers which fields to write/read through reflection which is usually slow b) it writes extra data to stream.
提高效率的一种方法是实现Externalizable及其writeExternal / readExternal方法。
One way to make it more efficient is to implement Externalizable and its writeExternal/readExternal methods.
这是一个问题:如果我改为提供'writeObject / readObject '方法并且不要在其中调用deafiltWriteObject / defaultReadObject,那么这个机制不会使用反射来确定要写入/读取的字段,而且它不会将额外的数据写入流(或者它会不确定)。那么从效率的角度来看,实现上面提到的writeObject / readObject与实现Externalizable一样吗?或者后一个选项是否提供了一些更实际的好处,前者没有?
Here's the question: if I instead provide 'writeObject/readObject' methods and don't call deafiltWriteObject/defaultReadObject in them, then this mechanism won't use reflection to figure out which fields to write/read, plus it won't write extra data to stream (or will it? not sure). So from an efficiency perspective, is implementing writeObject/readObject mentioned above same as implementing Externalizable? Or does the latter option give some more practical benefits which the former doesn't?
编辑:当然,是一个实现readObject / writeObject的Serializable类被子类化的差异,如果子类有自己的readObject / writeObject,则不需要调用super的readObject / writeObject。如果超级/子类改为实现Externalizable,则不是这样。在这种情况下,需要显式调用super的writeExternal / readExternal。 然而,从效率的角度来看,这种差异是无关紧要的。
a difference, ofcourse, is when a Serializable class implementing readObject/writeObject is subclassed, and if the subclass has its own readObject/writeObject, they don't need to call super's readObject/writeObject. Not so if the super/subclass instead implement Externalizable. In this case, super's writeExternal/readExternal need to be explicitly called. However, this difference is irrelevant from an efficiency point of view.
推荐答案
还有一些结束首先选择要调用哪个类/ writeObject / readObject。但它显着减少了。
There is still some over head in choosing which class/writeObject/readObject to call next. but it is significantly reduced.
这可以与Externalizable相同,具体取决于你在做什么,以及你是否使用它给你的额外选项。例如readObject假定您每次都创建一个新对象,Externalizable具有readResolve,这意味着您可以重用对象。
This can perform the same as Externalizable depending on what you are doing and whether you use the extra options it gives you. e.g. readObject assumes you to create a new object each time, Externalizable has readResolve which means you can reuse objects.
在许多情况下,回收对象是加速反序列化的下一步。 (假设这是你的选择)
In many cases, recycling objects is the "next" step in speeding up deserialization. (Assuming that's an option for you)
这篇关于Java:writeObject与writeExternal的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!