什么更快?一个intent.putExtras(Bundle with Strings)还是多个intent.putExtra(String)?

2024-02-02

什么更快?将一堆字符串值添加到bundle然后将其添加到intent?或者只是将值添加到intent using intent.putExtra()?还是没有太大区别?

谷歌搜索给了我教程,但没有太多答案。只是出于好奇而询问,想知道使用其中之一是否会影响性能。This https://stackoverflow.com/questions/11900266/intent-putextrastring-bundle-vs-intent-putextrabundle接近了,但没有回答我想知道的事情。


创造Bundle自己完成,然后将其添加到意图中应该会更快。

根据源代码 http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.4_r1.2/android/content/Intent.java#Intent.putExtra%28java.lang.String,boolean%29, Intent.putExtra(String, String)方法如下所示:

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

所以,它总是首先检查是否Bundle mExtras已经创建了。这就是为什么在添加大量字符串时它可能会慢一些。Intent.putExtras(Bundle)看起来像这样:

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

所以,它会检查if (mExtras == null)仅一次,稍后将所有值添加到内部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由一个支持Map (HashMap准确地说),因此一次将所有字符串添加到此映射中也应该比逐个添加字符串更快。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

什么更快?一个intent.putExtras(Bundle with Strings)还是多个intent.putExtra(String)? 的相关文章

随机推荐