Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how to implement Parcelable Vs. Serializable?

Tags:

java

android

After some time using the implementation Serializable in my classes on Java (Android) I discovered the Parcelable, but I couldn't find out when to choose one or another. Also what are the performance differences between them?

like image 737
Blanco Avatar asked Sep 15 '16 18:09

Blanco


People also ask

Why is Parcelable better than Serializable?

Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn't create more temp objects while passing the data between two activities.

Why do we use Parcelable instead of Serializable in Android?

Unlike Serializable, in Parcelable reflection won't be used so it is faster and has better performance. Android Parcelabe is not made to save objects into the files, so if you want to save an object in the file you must use Serializable.

What are Parcelable and Serializable and what is the difference between them?

Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations. Parcelable is an Android specific interface where you implement the serialization yourself.

Why do we use Parcelable?

Parcelable and Bundle objects are intended to be used across process boundaries such as with IPC/Binder transactions, between activities with intents, and to store transient state across configuration changes.


1 Answers

what are the performance differences between them?

Parcelable is signficantly faster than is Serializable for the places where you use Parcelable: Intent extras, saved instance state Bundle, etc.

That being said, assuming that you are not doing lots of this stuff, particularly in tight loops, users are unlikely to really notice the difference.

when to choose one or another

If you are doing Android development, prefer Parcelable to Serializable where Parcelable is an option. At most, use Serializable for data persistence, though I would recommend other serialization options even for that (e.g., JSON via Gson).

The one primary exception to this would be if your Java objects are in a separate library that would be used both from Android and from other Java environments. Those environments will not have Parcelable, but Serializable would work in both places.

like image 76
CommonsWare Avatar answered Oct 21 '22 03:10

CommonsWare