Kotlin

Kotlin

Made by DeepSource

Avoid explicitly triggering garbage collection KT-W1029

Anti-pattern
Major

The code explicitly triggers the garbage collector by calling System.gc() or similar methods.

In Kotlin, you don't need to explicitly trigger the garbage collector. The garbage collector automatically frees up memory by deallocating objects that are no longer needed. Explicitly triggering the garbage collector is not recommended because it can disrupt its natural flow and negatively impact performance. The garbage collector is optimized to run at the appropriate times, and manually invoking it can interfere with its efficiency.

To fix this issue, remove the explicit calls to trigger the garbage collector and let the garbage collector handle memory management automatically. The code should be designed in a way that it does not rely on explicit garbage collection calls.

Bad Practice

fun someFunction() {
  // some code
  System.gc() // explicit garbage collection call
  // some more code
}

Recommended

Remove all explicit calls to System.gc(), Runtime.getRuntime().gc(), or System.runFinalization().