Externalizable stores more data than Serializable ?
When trying to optimize some code (to reduce the amount of data transferred), i changed my class from Serializble to Externalizable. The methods required by Externalizable read/write a single int value. To my surprise this changed the number of bytes from 1310861 to 1704069! Does anybody know what I am doing wrong here?
import java.io.*;
publicclass SerializationTest{
publicstaticvoid main(String[] args){
try{
/* This uses Serializable
SimpleObject1[] objects = new SimpleObject1[128*1024];
for (int i=0; i<128*1024; ++i){
objects[i] = new SimpleObject1(i);
}
*/
// This used Externalizable
SimpleObject2[] objects =new SimpleObject2[128*1024];
for (int i=0; i<128*1024; ++i){
objects[i] =new SimpleObject2(i);
}
ByteArrayOutputStream byteOut =new ByteArrayOutputStream(10000000);
ObjectOutputStream objectOut =new ObjectOutputStream(new BufferedOutputStream(byteOut));
objectOut.flush();
long startTime = System.nanoTime();
objectOut.writeObject(objects);
objectOut.flush();
double totalTime = (System.nanoTime() - startTime) / 1E9;
byte[] buffer = byteOut.toByteArray();
System.out.println("Bytes written: " + buffer.length);
System.out.println("Total time: " + totalTime);
}catch (Exception e){
}
}
}
class SimpleObject1implements Serializable{
privateint value;
public SimpleObject1(){
super();
}
public SimpleObject1(int i){
super();
this.value = i;
}
}
class SimpleObject2implements Externalizable{
privateint value;
public SimpleObject2(){
super();
}
public SimpleObject2(int i){
super();
this.value = i;
}
publicvoid readExternal(ObjectInput in)throws IOException, ClassNotFoundException{
this.value = in.readInt();
}
publicvoid writeExternal(ObjectOutput out)throws IOException{
out.writeInt(this.value);
}
}

