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

1

8

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

Thad answered 25/8, 2016 at 18:20 Comment(5)
The example code you posted should not produce any boxing. I don't see any calls to Integer.valueOf in the bytecode.Interrelated
"On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int?) or generics are involved. In the latter cases numbers are boxed." - I guess that this is the problem here...Grainy
just saw that that's what you are told on your bug-report as wellGrainy
I'm sorry I didn't include that part of the story! I do happen to be using generics as Dmitry Petrov guessed.Updated the question with using generics.Thad
The suggested solution is to create specialised delegate classes for the primitive valuesNgo
A
4

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.

Antoniaantonie answered 29/8, 2016 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.