Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

serialization - Java: efficiency of writeObject vs writeExternal

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.

One way to make it more efficient is to implement Externalizable and its writeExternal/readExternal methods.

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?

EDIT: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is still some over head in choosing which class/writeObject/readObject to call next. but it is significantly reduced.

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.

http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/input.html

In many cases, recycling objects is the "next" step in speeding up deserialization. (Assuming that's an option for you)

http://vanillajava.blogspot.co.uk/2011/10/recycling-objects-to-improve.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...