英文:
Zeroing out memory of strings from matchResult in kotlin
问题
我有一个在 Kotlin 类中的函数:
fun doSmg(word: String) {
REGEX.matchEntire(word)?.groupValues?.let { groupValues ->
// 在下面可以使用 groupValues[1] 和 groupValues[2]
}
函数执行完成后,字符串 groupValues[1] 和 groupValues[2] 仍然存在于内存中吗?如果是的话,有没有办法将它们清除?
我查了一下 Java/Kotlin 反射,但我不确定它是否适用于这里。
英文:
I have a function that is part of a class in kotlin:
fun doSmg(word: String) {
REGEX.matchEntire(word)?.groupValues?.let { groupValues ->
// Use groupValues[1] and groupValues[2] below
}
Do the strings, groupValues[1] and groupValues[2], still exist in memory after the function completes? If so, is there a way to clear them?
I looked into using java/kotlin reflection, but I'm not sure if it even applies here.
答案1
得分: 1
Kotlin 在 JVM 上运行,因此它使用 JVM 的垃圾回收功能。在 JVM 中,如果一个内存中的对象与垃圾回收根对象之间没有路径连接,那么它将在下次垃圾回收运行时被标记为可回收。垃圾回收器将负责所有的内存清理工作。它何时被清理取决于系统。
那么什么是 GC 根对象?任何活动线程、任何堆栈变量、任何当前在任何线程上运行的函数的参数、任何 Class 对象、任何由 JNI 持有的引用以及任何静态变量。这些变量都没有引用这些变量,因此内存将被标记为可回收,并在下次垃圾回收运行足够深的扫描时进行清理。
英文:
Kotlin is running on the JVM, so it uses the garbage collection of the JVM. In the JVM, if there is no path between an object in memory and a garbage collection root object, then it is eligible for collection the next time garbage collection runs. The garbage collector will take care of all memory cleanup. When it will be cleaned up is up to the system.
So what's a GC root? Any active thread, any stack variable, any parameter to a function that's currently running on any thread, any Class objects, any reference held by JNI, and any static variable. None of those are holding a reference to those variables here, so the memory will be eligible for collection and cleaned up the next time the GC runs a deep enough sweep.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论