微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 什么更快?一个intent.putExtras(捆绑带字符串)或许多intent.putExtra(字符串)?

什么更快?将一堆字符串值添加一个包中,然后将其添加一个意图?或者只是使用intent.putExtra()将值添加到intent中?或者它没有太大区别?

谷歌搜索给了我教程,但没有太多答案.只是出于好奇,想知道是否会影响使用其中一个性能. This接近了,但没有回答我想知道的事情.

最佳答案
自己创建Bundle然后将其添加到intent应该更快.

根据source code,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.这就是为什么对于大量的String添加可能会慢一点. Intent.putExtras(Bundle)看起来像这样:

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

因此,它将仅检查(mExtras == null)一次,然后使用Bundle.putAll()将所有值添加到内部Bundle mExtras:

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)备份,因此将所有字符串一次添加到此映射也应该比逐个添加字符串更快.

原文地址:https://www.jb51.cc/android/430918.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐