Sunday, April 17, 2011

Difference in sizes when you serialize using Serializable interface and serialize using Externalizable interface

Let's take a simple case, an object of type SimpleClass with just few fields - firstName, lastName, weight and location, containing data {"Brad", "Pitt", 180.5, {49.345, 67.567}}. When you serialize this object that is about 24 bytes by implementing Serializable interface, it turns into 220 bytes (approx). As it turns out, the basic serialization mechanism stores all kinds of information in the file so that it can deserialize without any other assistance. Look at the format below when the object is serialized and you will understand why it is turned out to 200 bytes.

Length: 220
Magic: ACED
Version: 5
OBJECT
CLASSDESC
Class Name: "SimpleClass"
Class UID: -D56EDC726B866EBL
Class Desc Flags: SERIALIZABLE;
Field Count: 4
Field type: object
Field name: "firstName"
Class name: "Ljava/lang/String;"
Field type: object
Field name: "lastName"
Class name: "Ljava/lang/String;"
Field type: float
Field name: "weight"
Field type: object
Field name: "location"
Class name: "Ljava/awt/Point;"
Annotation: ENDBLOCKDATA
Superclass description: NULL
STRING: "Brad"
STRING: "Pitt"
float: 180.5
OBJECT
CLASSDESC
Class Name: "java.awt.Point"
Class UID: -654B758DCB8137DAL
Class Desc Flags: SERIALIZABLE;
Field Count: 2
Field type: integer
Field name: "x"
Field type: integer
Field name: "y"
Annotation: ENDBLOCKDATA
Superclass description: NULL
integer: 49.345
integer: 67.567


Now if you serialize the same by extending Externalizable interface, the size will be reduced drastically and the information saved in the persistant store is also reduced a lot. Here is the result of serializing the same class, modified to be externalizable. Notice that the actual data is not parseable externally any more--only your class knows the meaning of the data!


Length: 54
Magic: ACED
Version: 5
OBJECT
CLASSDESC
Class Name: "SimpleClass"
Class UID: 5CB3777417A3AB5BL
Class Desc Flags: EXTERNALIZABLE;
Field Count: 0
Annotation
ENDBLOCKDATA
Superclass description
NULL
EXTERNALIZABLE:
[70 00 04 4D 61 72 6B 00 05 44 61 76 69 73 43 3C
80 00 00 00 00 01 00 00 00 01]


No comments:

Post a Comment

Chitika