Kotlin的Float,Int等优化为JVM中的内置类型吗? [英] Are Kotlin's Float, Int etc optimised to built-in types in the JVM?

查看:201
本文介绍了Kotlin的Float,Int等优化为JVM中的内置类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Kotlin的新手,AFAICT的语法只支持Int,Float等对象版本,没有Java的相应int和float原语。但是如果可能的话,编译器或JVM是否会优化使用原始类型?我担心如果我在一个从游戏主循环调用的函数中使用局部变量,那么如果JVM每次都必须创建一个对象而不是使用原始类型,则可能会导致GC口吃。

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.

推荐答案

引用文档 b
$ b

Quoting the docs:


某些类型可以有特殊的内部表示 - 例如数字,字符和布尔值可以表示为图元运行时的值 - 但对于用户来说,它们看起来像普通的类。在本节中,我们将介绍Kotlin中使用的基本类型:数字,字符,布尔值,数组和字符串。

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原始类型在运行时使用。当然有一些例外:
$ b

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


在Java平台上,数字在物理上存储为JVM基元类型,除非我们需要可以为空的数字引用(如Int?)或泛型。在后一种情况下,数字被装箱。

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.

源文档中还有一个提示,例如 Int

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


表示一个32位有符号整数。在JVM上,这种类型的非空值被表示为基本类型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.

这篇关于Kotlin的Float,Int等优化为JVM中的内置类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆