gpt4 book ai didi

android - 使用处理程序、消息和包最小化内存分配

转载 作者:搜寻专家 更新时间:2023-11-01 08:14:33 26 4
gpt4 key购买 nike

我有一个 activity 不断(每秒几次)通过 AIDL 将 byte[] 数据发送到 service服务使用消息-bundle*将这些消息转发到网络线程的处理程序。网络线程还不断接收数据,并将其作为消息-bundle 发送到servicehandlerservice 通过 AIDL 将这个 bundle 发送到其他 activity

如您所知,为 bundle 分配了大量内存。

在 DDMS 上查看我的内存分配后,我看到内存分配给:

  • 正在初始化的bundle
  • 正在创建的 HashMap
  • 我将作为条目添加到哈希表中的 byte[] 数据

我想尽可能少地减少内存分配。

有没有比通过消息包发送 byte[ ] 跨 Activity/线程更好的方法?

*message-bundle,我的意思是 messagebundle 作为数据

尝试过:创建一个 bundle 对象池,但效果不是很好——很难在 Activity 之间进行管理,而且我不知道如何使用 预先分配它>byte[] 数据...

最佳答案

那些字节数组真的有那么大,您真的需要担心吗?在不了解您的应用程序的情况下,我猜想您所描述的应用程序的瓶颈将在网络处理程序中,而不是服务和 Activity 之间的消息传递。除非您在某处泄漏 Bundle,否则 GC 应该处理所有未使用的内存并恢复它以供您的应用重用。

如果有的话,我会尽量使这些数组足够小(以避免一次分配和回收大量内存)并改为发送几条小消息。这样,应用程序就不会一次性消耗所有可用内存,而是让 GC 以宽松的时间表(即,当 CPU 空闲时)完成其工作,而不是强制 GC 立即收集对象。

当然,您应该在自己的应用中测试什么是“太大”或“足够小”,并衡量采用一种或另一种方法的 yield (如果有的话)。

更新:

an android dev site article 逐字复制:

In a performance-sensitive code path, such as the layout or drawing method of a view or the logic code of a game, any allocation comes at a price. After too many allocations, the garbage collector will kick in and stop your application to let it free some memory. Most of the time, garbage collections happen fast enough for you not to notice. However, if a collection happens while you are scrolling through a list of items or while you are trying to defeat a foe in a game, you may suddenly see a drop in performance/responsiveness of the application. It's not unusual for a garbage collection to take 100 to 200 ms. For comparison, a smooth animation needs to draw each frame in 16 to 33 ms. If the animation is suddenly interrupted for 10 frames, you can be certain that your users will notice.

根据您的评论,我会重新考虑 GC 是否与您的情况相关。堆限制 may vary between 16 and 32 MB (并且上限可能正在增长)。假设每秒分配 10 次,每次分配 64 字节,您将每 30 分钟(大约)分配 1 MB。如果 GC 需要 200 毫秒来释放该内存,影响可以忽略不计。我知道这里的数字没有考虑 HashMap 或 bundle 所需的内存,但它们仍然与让您了解我们正在谈论的数量级有关。现在,考虑网络请求从网络中获取这 64 个字节需要多少时间。即使它只需要 50 毫秒,也只是 GC 所需时间的 1/4 到 1/2,每个网络请求。这甚至没有考虑您的 Activity 处理该数据所需的时间。

因此,总而言之,在重组您的代码以提高其效率之前,请确保您正在修改的步骤实际上是一个瓶颈,否则您的所有努力可能会白费。只是我的 0.02 美元。

关于android - 使用处理程序、消息和包最小化内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6148114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com