伴随对象是否在应用程序的生命周期中保留在内存中 [英] Do companion objects remain in memory for app's lifecycle
问题描述
在Kotlin中,您可以使用一个伴随对象创建一个单例:
In Kotlin, you can create a singleton using a companion object:
class MyClass {
companion object {
fun doSomething() {
}
}
}
根据Kotlin文档,它指出:
According to the Kotlin docs, it states:
请注意,即使伴随对象的成员看起来像 其他语言的静态成员,在运行时仍是实例 真实对象的成员...
Note that, even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects...
https://kotlinlang.org/docs/reference/object-declarations.html
这是否意味着在伴侣对象中使用函数后,类的实例(MyClass)会在应用程序的整个生命周期中保留在内存中? Android Studio中有没有办法检查是否是这种情况?
Does this mean that after using a function in the companion object, the instance of the class (MyClass) remains in memory for the entire lifecycle of the app? Is there a way in Android Studio to check to see if this is the case?
推荐答案
类实例(MyClass)在应用程序的整个生命周期中都保留在内存中 ?
instance of the class (MyClass) remains in memory for the entire lifecycle of the app?
JVM中的伴侣对象
科特林
class MyClass {
companion object {
fun doSomething() {
}
}
}
在JVM中转换的MyClass(Kotlin)
public final class MyClass {
public static final MyClass.Companion Companion = new MyClass.Companion(null);
public static final class Companion {
public final void doSomething() {
}
private Companion() {
}
public Companion() {
this();
}
}
}
如上面的代码,companion object
在JVM中被声明为Companion
类,并且在MyClass
类中被创建为static
字段.因此,不会被gc收集.因此,对象(Companion)的内存在ProcessLifecycle
期间保留. static final object
在正常情况下不会释放.
As above code, companion object
is declared as Companion
class in JVM, and it's created as static
field inside MyClass
class. Thus, isn't collected by gc. So, the memory of object(Companion) is remained during the ProcessLifecycle
. static final object
isn't released in normal case.
最后,如果在应用程序中引用了MyClass.Companion
实例,则该实例将不会被垃圾回收. (在通用的Classloader上).
In conclusion, if referred to MyClass.Companion
instance in application, that instance will not be garbage collected. (on general Classloaders).
*如果未在应用程序中引用MyClass.Companion
实例,则可以通过代码收缩功能将其删除.
*If not referred to MyClass.Companion
instance in application, it may be removed by code shrinking feature.
Android Studio中是否有一种方法可以检查是否是这种情况?
Is there a way in Android Studio to check to see if this is the case?
您可以通过 android studio>分析器>堆转储查看.
- https://developer.android.com/topic/performance/memory-overview
- https://developer.android.com/studio/build/shrink-code
- https://developer.android.com/topic/performance/memory-overview
- https://developer.android.com/studio/build/shrink-code
这篇关于伴随对象是否在应用程序的生命周期中保留在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!