Parcelable vs Serializable

This article has a good explanation of Parcelable vs Serializable. In summary, the downside of serializable is that the run time needs to invoke reflection while serializing each class member, which may be a performance drain for bigger objects that are serialized more frequently. Parcelable solves this problem by explicitly defining how each class member should be serialized. As part of implementing Parcelable, the writeToParcel method should be over-ridden. Some code:

public class DataObject implements Parcelable {
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(strMember1); // Parcelable for strings
        dest.writeInt(member2); // Parcelable for integers                                                                                                                                  

        dest.writeBooleanArray(new boolean[] {boolMember1, boolMember1} ); // Parcelable for booleans

        // Caution: missing data members don’t get serialized

   public void readFromParcel(Parcel source) {
        strMember1 = source.readString();
        member2 = source.readInt();
        // readFromParcel for boolean members
        boolean[] flags = source.createBooleanArray();
        boolMember1 = flags[0];

However, the catch in implementing Parcelable is for large objects, that each time a new class member is added, its the responsibility of the developer to also the add corresponding code in the writeToParcel method. If this is not done, this new class member will not be serialized and the default value when de-serializing the object will be null.

Hence, while deciding whether to implement Parcelable, the trade off is between a minor improvement in performance (vs.) the possibility of introducing errors due to missed writeToParcel implementation for new class members and additional unit testing involved in testing the parceling methods.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s