Search code examples
androidkotlinreflection

Zeroing out memory of strings from matchResult in 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.


Solution

  • 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.