Java Reference
In-Depth Information
private
private void
void writeObject ( ObjectOutputStream oos ) throws
throws IOException {
oos . defaultWriteObject ();
oos . writeInt ( x );
oos . writeInt ( y );
}
private
private void
void readObject ( ObjectInputStream ois )
throws
throws IOException , ClassNotFoundException {
ois . defaultReadObject ();
x = ois . readInt ();
y = ois . readInt ();
}
}
Serializing 100,000 of these objects on my machine still takes 132 ms, but deserializing them
takes only 468 ms—a 30% improvement. If deserializing a simple object is what takes a sig-
nificant portion of time in a program, then it might make sense to optimize it like this. Be
aware, however, that it makes the code harder to maintain as fields are added, moved, and so
on.
So far, though, the code is more complex but is still functionally correct (and faster). But be-
ware of using this technique in the general case:
public
public class
class TripHistory
TripHistory implements
implements Serializable {
private
private transient
transient Point [] airportsVisited ;
....
// THIS CODE IS NOT FUNCTIONALLY CORRECT
private
private void
void writeObject ( ObjectOutputStream oos ) throws
throws IOException {
oos . defaultWriteObject ();
oos . writeInt ( airportsVisited . length );
for
for ( int
int i = 0 ; i < airportsVisited . length ; i ++) {
oos . writeInt ( airportsVisited [ i ]. getX ());
oos . writeInt ( airportsVisited [ i ]. getY ());
}
}
private
private void
void readObject ( ObjectInputStream ois )
throws
throws IOException , ClassNotFoundException {
ois . defaultReadObject ();
int
int length = ois . readInt ();
airportsVisited = new
new Point [ length ];
for
for ( int
int i = 0 ; i < length ; i ++) {
airportsVisited [ i ] = new
new Point ( ois . readInt (), ois . readInt ();
}
Search WWH ::




Custom Search