Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my software, I have some various values which use property delegation.

This is a simple similar example showing what I do:

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)

What I've noticed, however, is that referring to this value seems to create an autoboxed object (java.lang.Integer) on EVERY reference. Because the value must be referenced potentially millions or times per second, this results in massive garbage creation for my software; heavy stress is put on the garbage collector.

Is there a way to avoid the overhead? If not directly, are there any clever ways to "emulate" property delegation that are performant?

enter image description here

Submitted a bug report on YouTrack: https://youtrack.jetbrains.com/issue/KT-13606

like image 486
Jire Avatar asked Aug 25 '16 18:08

Jire


1 Answers

As discussed in the bug report, your app generates garbage because your property delegate is generic, and therefore requires boxing of values. If you use a non-generic property delegate with a primitive type, no boxing happens.

like image 99
yole Avatar answered Oct 06 '22 23:10

yole