How costly is casting in Kotlin?

Viewed 1025

In Kotlin, how costly is the casting of classes?

So for instance, let's have the following Test class

open class Test {
    open fun question() = "Basic question"
}

and 3 inheriting classes

class MathTest : Test() {
    override fun question() = "2+2=?"
}

class EnglishTest : Test() {
    override fun question() = "Who created SO?"
}

class HistoryTest: Test() {
    override fun question() = "When was SO created?"
}

How costly would it be to cast (for instance, let's say) 100 Test objects to either one of these 3, at runtime, in Android (and in general) ?

1 Answers

I messed around a little bit with disassembling the generated bytecode, and except for one case, casting is identical to Java. The one case where it seems to be different is when using the safe cast operator, as?, like so:

val thing = "" as? Int

This generates equivalent bytecode to this Java code:

String _temp = "";
if (!(_temp instanceof Integer)) {
    _temp = null;
}
Integer thing = (Integer) _temp;

This makes it slightly more expensive than a regular cast in Java. However, there is no direct equivalent to this behavior in Java, short of writing a similar if statement anyways, so I think it's safe to say that casting in Kotlin is no more expensive than casting in Java.

Related