5

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.

4

1 回答 1

4

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.

于 2013-08-01T10:29:19.633 回答