Kotlin: How can I avoid autoboxing (garbage) in delegated properties?

In my software, I have several different values ​​that use property delegation.

This is a simple example showing what I'm doing:

class ExampleDelegate<T>(val value: T) { operator fun getValue(thisRef: Any?, property: KProperty<*>) = value } val example by ExampleDelegate(1000) // number larger than 127 (no box cache) 

However, I noticed that accessing this value is similar to creating an object with an autoobject ( java.lang.Integer ) in EVERY link. Since the value should refer to potentially millions or times per second, this leads to massive garbage creation for my software; heavy stress is applied to the garbage collector.

Is there a way to avoid overhead? If not directly, are there any clever ways to imitate the delegation of properties that are performative?

enter image description here

YouTrack bug report sent: https://youtrack.jetbrains.com/issue/KT-13606

+8
properties autoboxing delegates kotlin garbage
source share
1 answer

As discussed in the bug report report , your application generates garbage because your property delegate is shared and therefore requires a box of values. If you use a delegate with non-native properties with a primitive type, no boxing occurs.

+4
source share

All Articles