gpt4 book ai didi

casting - 在 Kotlin 中类型转换的成本是多少?

转载 作者:行者123 更新时间:2023-12-02 12:20:17 26 4
gpt4 key购买 nike

在 Kotlin 中,类的转换成本有多大?

例如,让我们有以下 Test类(class)

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

和 3 个继承类
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?"
}

转换(例如,假设)100 Test 的成本是多少在运行时,在 Android 中(以及一般情况下)对象到这 3 个中的任何一个?

最佳答案

我在反汇编生成的字节码时搞砸了一点,除了一种情况外,转换与 Java 相同。似乎不同的一种情况是使用 the safe cast operator 时, as? ,像这样:

val thing = "" as? Int

这将生成与此 Java 代码等效的字节码:
String _temp = "";
if (!(_temp instanceof Integer)) {
_temp = null;
}
Integer thing = (Integer) _temp;

这使得它比 Java 中的常规转换稍贵。然而,在 Java 中没有直接等价于这种行为,除了写一个类似的 if无论如何,我认为可以安全地说 Kotlin 中的转换并不比 Java 中的转换贵。

关于casting - 在 Kotlin 中类型转换的成本是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52296619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com