Reputation: 135
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?
Upvotes: 8
Views: 6831
Reputation: 549
Parcelable is better for android: 1. It's faster 2. It doesn't use reflection (Serializable uses Reflection)
Upvotes: -1
Reputation: 103
Parcelable assists in passing data between Android components. Binder marshals the Parcel to be sent, sends and receives it, and then unmarshals it on the other side to reconstruct a copy of the original Parcel.
w.r.t Serializable you only need to implement the Serializable interface on a class and its children. It is a marker interface, meaning that there is no method to implement, Java will simply do its best effort to serialize it efficiently.It uses Reflection that tends to create a lot of temporary objects and cause quite a bit of garbage collection.
Per the google engineers Parcelable is more than 10x faster than Serializable. In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage objects in comparison to Serialization.
You may check sample code here to understand the implementation difference- Android: Difference between Parcelable and Serializable?
Be Careful?
Check the following projects to avoid writing Parcelable manually.
Upvotes: 4
Reputation: 1006674
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.
Upvotes: 13