1

I'm reading Java Performance: The Definitive Guide, in the Overriding Default Serialization section, the author declared that, deserializing the following class

public class Point implements Serializable {
    private int x;
    private int y;
    ...
}

is 30% slower than deserializing the following class

public class Point implements Serializable {
    private transient int x;
    private transient int y;
    ....
    private void writeObject(ObjectOutputStream oos) throws IOException {
        oos.defaultWriteObject();
        oos.writeInt(x);
        oos.writeInt(y);
    }
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        ois.defaultReadObject();
        x = ois.readInt();
        y = ois.readInt();
    }
}

Why? I think the time spent deserializing them should be equal because the second class doesn't do anything special.

Searene
  • 25,920
  • 39
  • 129
  • 186
  • 2
    Because the default serialisation mechanism needs to use some form of reflection (doesn't need to be java.lang.reflect; it can be something JVM internal - the docs don't mandate) which is not optimized as much as ordinary Java code that goes through the HotSpot JVM and gets compiled to efficient native code if it is invoked enough times. – Erwin Bolwidt Dec 16 '19 at 00:27
  • 2
    Some additional ones that apply here (but not all of them, as that question is about why (de)serialization is slow in general) can be found here: https://stackoverflow.com/questions/19447623/why-javas-serialization-slower-than-3rd-party-apis (like, "inefficient coding") – Erwin Bolwidt Dec 16 '19 at 00:30
  • @ErwinBolwidt Thanks, it's really helpful. Have you considered posting an answer to sum it up? – Searene Dec 17 '19 at 00:26

0 Answers0