Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]

江枫思渺然 提交于 2019-12-08 02:42:54

问题


I'm new to Kotlin, and AFAICT its syntax only supports the object versions of Int, Float etc without the corresponding int and float primitives of Java. But does the compiler or JVM optimise to use the primitive types if possible? I'm concerned that if I use local variables in a function called from a game main loop it might cause GC stutter if the JVM has to create an object each time instead of using a primitive type.


回答1:


Quoting the 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.

So yes, the compiler does optimise in a way that the JVM primitive types are used at runtime. There are certain exceptions of course:

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.

There's also a hint in the source documentation, e.g. Int:

Represents a 32-bit signed integer. On the JVM, non-nullable values of this type are represented as values of the primitive type int.



来源:https://stackoverflow.com/questions/47080723/are-kotlins-float-int-etc-optimised-to-built-in-types-in-the-jvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!