Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a serializable object always get serialized when put in a bundle?

We were wondering if when using Bundle with serializable or parcelable objects, when does the marshalling actually happen? As soon as you put it in the bundle? Since bundles are mostly used to simply pass around data between two screens (we're not even talking about IPC here!), there doesn't seem to be much point in marshalling an object, since it stays in memory all the time, no?

Are we right in assuming that marshalling (be it Java serializing or Android parcelling) only happens if

  1. the data must be passed to another process, e.g. during RMI, or
  2. the component (activity or service) gets destroyed and instance state must be written to disk?

I've seen Android framework engineers (I believe it was Dianne Hackborn) say that one should use Parcelable instead of Serializable because the former is much faster. How much faster? And will this even make a difference if the object isn't marshalled most of the time anyway (assuming our assumptions about this were right)?

like image 575
Matthias Avatar asked Aug 24 '10 07:08

Matthias


1 Answers

I think I've figured it out. I basically spent the entire last day and most of today on debugging through the Android Parcel and Bundle source code, and here is how it works:

  • a Bundle is basically just a wrapper around a HashMap, but it supports to parcel (i.e. marshal) that internal map and its contents
  • if you put a value into a Bundle, it will first unparcel this internal map, and then simply put the value into that map
  • unparceling the map happens lazily: it will only unparcel it if you're trying to access it (e.g. by calling bundle.putParcelable()). Even then, it will only unparcel the map itself, but not its values. Only when you try to actually access these values (e.g. using bundle.getParcelable("key")) it will unparcel the value, too. In other words, if you parcel something that's inside a Bundle, unparcelling will not occur if you never access these values again.

So generally: NO, a value is not parceled simply by putting it into a Bundle. Instead, parcelling happens when passing the Bundle to another component (activity or service; why Android does that, I don't know, since no IPC is happening technically.) or when it otherwise has to be parcelled.

like image 65
Matthias Avatar answered Oct 18 '22 04:10

Matthias