Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster? One intent.putExtras(Bundle with Strings) or many intent.putExtra(String)?

What is faster? Adding a bunch of string values to a bundle and then adding that to an intent? Or just adding the values to an intent using intent.putExtra()? Or doesn't it make much difference?

A Google search gave me tutorials, but not much of an answer. Just asking out of curiosity, wondering if it would affect performance to use one or the other. This got close, but does not answer what I would like to know.

like image 617
Lunchbox Avatar asked Oct 03 '22 09:10

Lunchbox


1 Answers

Creating Bundle on your own and then adding that to an intent should be faster.

According to the source code, Intent.putExtra(String, String) method looks like this:

public Intent putExtra(String name, String value) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putString(name, value);
    return this;
}

So, it will always check at first if Bundle mExtras was already created. That's why it's probably a bit slower with big sequence of String additions. Intent.putExtras(Bundle) looks like this:

public Intent putExtras(Bundle extras) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putAll(extras);
    return this;
}

So, it will check if (mExtras == null) only once and later add all the values to the internal Bundle mExtras with Bundle.putAll():

public void putAll(Bundle map) {
     unparcel();
     map.unparcel();
     mMap.putAll(map.mMap);

     // fd state is now known if and only if both bundles already knew
     mHasFds |= map.mHasFds;
     mFdsKnown = mFdsKnown && map.mFdsKnown;
 }

Bundle is backed up by a Map (HashMap to be precise), so adding all Strings at once to this map should be also faster than adding Strings one by one.

like image 125
Adam Stelmaszczyk Avatar answered Oct 12 '22 11:10

Adam Stelmaszczyk