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

1

2

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.

Omaromara answered 2/11, 2017 at 16:56 Comment(0)
E
2

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.

Equities answered 2/11, 2017 at 16:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.