Kotlin Android 扩展 vs Android 数据绑定库,内存使用

Kotlin Android Extensions vs Android Data Binding Library, memory usage

我对两种情况下使用的内存有疑问 ->Android 数据绑定与 Android Kotlin 扩展。 在哪种情况下设备上使用的内存会更少?

Kotlin Android-extension 首先调用 findViewById,然后,结果将存储在本地缓存中。这意味着内存已用。

DataBinding 通过创建的绑定 class 在布局和 activities/fragments 之间创建路径。

当我们考虑用户设备上的内存使用情况时,我关心的是使用效率更高的那个。 谁能帮我找出答案?我倾向于说 dataBinding 更有效率。 是个类似的问题,但不是效率方向。

谢谢!

tldr: 据我所知,内存使用情况没有区别,除非您不使用布局的所有视图。两者都缓存视图,但是在数据绑定初始化所有视图时,andoid kotlin 会按需获取。根据性能,kotlin 扩展在 fragment/activity 创建期间比数据绑定稍微快(我会说在大多数情况下无法识别)。

Kotlin 文档Android 扩展:

Adds a hidden caching function and a field inside each Kotlin Activity. The method is pretty small so it doesn't increase the size of APK much. Replaces each synthetic property call with a function call.

How this works is that when invoking a synthetic property, where the receiver is a Kotlin Activity/Fragment class that is in module sources, the caching function is invoked. For instance, given

class MyActivity : Activity() fun MyActivity.a() { 
         this.textView.setText(“”) 
}

a hidden caching function is generated inside MyActivity, so we can use the caching mechanism.

However in the following case:

fun Activity.b() { 
    this.textView.setText(“”)
}

We wouldn't know if this function would be invoked on only Activities from our sources or on plain Java Activities also. As such, we don’t use caching there, even if MyActivity instance from the previous example is the receiver.

原因:Kotlin 使用合成属性,并且使用缓存功能按需调用这些属性(因此 Activity/Fragment 加载速度稍快),而数据绑定一次绑定所有视图(这会消耗更多时间)。