1

I'm trying to figure out what is the most efficient way to pass an object from one activity to another in android. I read I can extend an object as Parcelable or Serializable, and it seems like Parcelable is the clear winner in terms of performance.

Now I just thought of a different way. Instead of extending any class, I'll put all my data variables into a bundle, pass those data, and reconstruct the object. For example:

public class myObject {
   // Data Variables
   private String str1;
   private String str2;
   private boolean bool1;

   // Constructor
   public myObject(String str1, String str2, boolean bool1){
      this.str1 = str1;
      this.str2 = str2;
      this.bool1 = bool1;
   }
}

Now I'll just pass the variables:

Intent i = new Intent();
i.setClass(ActOne.this, ActTwo.class);
Bundle bundle = new Bundle();
bundle.putString("KEY_STR1", str1);
bundle.putString("KEY_STR2", str2);
bundle.putBoolean("KEY_BOOL1", bool1);
startActivity(i);

In the ActTwo class, I'll get the data from the intent and reconstruct my object:

myObject newObjHolder = new myObject(str1, str2, bool1);

How does this way compare to passing a Parcelable? Faster? Slower? Barely any difference?

kyrax
  • 1,192
  • 3
  • 13
  • 29
  • it the same thing. Internally you write and read In/from the parcel object. – Blackbelt Sep 11 '14 at 16:36
  • http://www.developerphil.com/parcelable-vs-serializable/ – bhowden Sep 11 '14 at 16:37
  • To add another method, if you are sharing the same objects between many Activities, you may want to look at using a singleton approach rather than passing them. – Dan Harms Sep 11 '14 at 16:37
  • singleton has problems with state non-determinism. hence, you may find spooky... indeterminable outputs from class methods. – bhowden Sep 11 '14 at 16:41

1 Answers1

0

if you look a bit closer you'll see that Bundle is just a Parcelable anyway. So probably you're looking into a couple but very very small, miliseconds less efficient to do that way you're suggesting.

I'll tell you why: Parcelables has to write in a Parcel and you're writting in a Bundle, then this Bundle will write it to the Parcel. So you do add some overhead, but probably you can do a test similar to the link pointed by @bhowden and see that it will be very small.

So then you have to decide if you prefer the easy of code of Bundle or the speed of Parcelable.

Budius
  • 39,391
  • 16
  • 102
  • 144