kotlin icon indicating copy to clipboard operation
kotlin copied to clipboard

JVM IR: Optimize equality on class literals

Open sfs opened this issue 3 years ago • 2 comments

In common code in a multiplatform project the KotlinGenerateEqualsAndHashcodeAction generates equals methods containing a check of the form this::class == other::class. This is slower than code using javaClass on Kotlin/JVM since it contains additional calls to kotlin.jvm.internal.Reflection.getOrCreateKotlinClass.

This PR optimizes this check in the JVM IR backend, by replacing a::class == b::class with a.javaClass === b.javaClass.

sfs avatar Jul 27 '22 19:07 sfs

KClass.equals uses javaObjectType to compare underlying classes, so behavior in this case will change:

fun f(a: Any): Boolean =
    a::class == Int::class

fun main() {
    println(f(42))  // Should be true
}

udalov avatar Jul 28 '22 23:07 udalov

I completely missed that. I've changed the code to always compare boxed class types and added a test for boxed against unboxed primitive class comparisons.

In effect, this is implementing javaObjectType as an intrinsic in the Equals implementation. I didn't turn a::class.javaObjectType itself into an intrinsic since this pattern doesn't seem to be very common.

sfs avatar Aug 01 '22 15:08 sfs

Merged in a90c4d5dd54a289a96b7e167c5c75d67656f1d49 with minor corrections. Thanks!

udalov avatar Aug 22 '22 22:08 udalov