我是 Kotlin 新手,AFAICT 其语法仅支持 Int、Float 等对象版本,而不支持 Java 相应的 int 和 float 原语。但是如果可能的话,编译器或 JVM 是否会优化以使用原始类型?我担心如果我在游戏主循环调用的函数中使用局部变量,如果 JVM 必须每次都创建一个对象而不是使用原始类型,则可能会导致 GC 断断续续。
最佳答案
引用docs :
Some of the types can have a special internal representation - for example, numbers, characters and booleans can be represented as primitive values at runtime - but to the user they look like ordinary classes. In this section we describe the basic types used in Kotlin: numbers, characters, booleans, arrays, and strings.
所以,是的,编译器确实以 JVM primitive types 的方式进行优化。在运行时使用。当然也有一些异常(exception):
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.
源文档中还有一个提示,例如整数
:
Represents a 32-bit signed integer. On the JVM, non-nullable values of this type are represented as values of the primitive type int.
关于garbage-collection - Kotlin 的 Float、Int 等是否针对 JVM 中的内置类型进行了优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47080723/