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

Jire
  • 9,680
  • 14
  • 52
  • 87
  • 3
    The example code you posted should not produce any boxing. I don't see any calls to `Integer.valueOf` in the bytecode. – Alexander Udalov Aug 25 '16 at 20:25
  • 1
    "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... – Lovis Aug 26 '16 at 13:25
  • 1
    just saw that that's what you are told on your bug-report as well – Lovis Aug 26 '16 at 13:26
  • 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. – Jire Aug 26 '16 at 19:03
  • 1
    The suggested solution is to create specialised delegate classes for the primitive values – RobCo Jun 30 '17 at 11:29

1 Answers1

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.

yole
  • 92,896
  • 20
  • 260
  • 197