Java Reference
In-Depth Information
The JDK provides a default mechanism to serialize objects that implement either the Seri-
alizable or Externalizable interface. The serialization performance of practically every
object imaginable can be improved from the default serialization code, but this is definitely
one of those times when it would be unwise to perform that optimization prematurely. The
special code to serialize and deserialize the object will take a fair amount of time to write,
and the code will be harder to maintain than code that uses default serialization. Serialization
code can also be a little tricky to write correctly, so attempting to optimize it increases the
risk of producing incorrect code.
Transient Fields
In general, the way to improve object serialization cost is to serialize less data. This is done
by marking fields as transient , in which case they are not serialized by default. Then the
class can supply special writeObject() and readObject() methods to handle that data. If
the data isn't needed, then it is sufficient simply to mark it as transient .
Overriding Default Serialization
The writeObject() and readObject() methods allow complete control over how data is
serialized. With great control comes great responsibility: it's easy to get this wrong.
To get an idea of why serialization optimizations are tricky, take the case of a simple Point
object that represents a location:
public
public class
class Point
Point implements
implements Serializable {
private
private int
int x ;
private
private int
int y ;
...
}
On my machine, 100,000 of these objects can be serialized in 133 ms, and deserialized in
741 ms. But even as simple as that object is, it could—if very, very hard pressed for perform-
ance—be improved:
public
public class
class Point
Point implements
implements Serializable {
private
private transient
transient int
int x ;
private
private transient
transient int
int y ;
....
Search WWH ::




Custom Search