Java Serialization impact of unused variables

Java serialization is a process of saving an object’s state to a byte stream and rebuilding the bytes into a Java object (may be at some future time).

As serialization is a concept based on maintaining the state of the object, so every attribute inside the object will have an impact on the amount of data serialized.

To explain the impact of unused variables on Java serialization lets take an example.


Say we have a base class which has a variable and never used

public class BaseClass implements Serializable{
private String []test1 = null;
}

and we have a subclass extending the above class

public class SubClass extends BaseClass implements Serializable{
private String s1 = null;

public void init(){
s1 = “S”;
}
}

Now, say we write another file which persist the later class

public class FlattenTime {
public static void main(String [] args)
{
String filename = “test.ser”;
if(args.length > 0){
filename = args[0];
}
SubClass sc = new SubClass();
sc.init();
FileOutputStream fos = null;
ObjectOutputStream out = null;
try{
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(sc);
out.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}

Now as a output, the size of the “test.ser” is found as 114 bytes.

Lets make the subclass not to extend any other class

public class SubClass implements Serializable{
private String s1 = null;

public void init(){
s1 = “S”;
}
}

and now lets run the “FlattenTime” class; Now as a output, the size of the “test.ser” is found as 59 bytes.

You can notice as the number of attributes in the base class increases, the difference in the byte size increases between both the cases.

With this example, we can summarize that unused variables doesnt occupy memory but occupies space for serialization, So do remember the unused attributes (which mostly gets inherited from a hierarchy) when you are transfering objects over the network.

Written by Ravi Nallakukkala on April 4th, 2007 with no comments.
Read more articles on Java/ J2EE.

Related articles

No comments

There are still no comments on this article.

Leave your comment...

If you want to leave your comment on this article, simply fill out the next form:




You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> .