使用 Kotlin 的数字运算是否与使用 Java 基元的等效运算一样快?

Are number operations using Kotlin as fast as the equivalent with Java primitives?

Java 有原语,因为使用它们比基于 class 的对应物导致更多 efficient, readable, and less error prone code

Kotlin 是否执行编译时优化以确保数字运算的执行水平与 Java 原语相同(或更好)?

引用 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 的方式进行了优化。当然也有一些例外:

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:

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 也使用原语。但请注意:

  1. "less error-prone" 的原因在 Kotlin 中并不适用:盒装类型不可为 null,除非您要求它(就像基元一样)并且您不能混淆 ==equals

  2. "more readable" 也不行:您可以对两者使用运算符。

  3. "more efficient" 部分确实非常适用,但您不能犯链接问题顶部答案中提到的单字符印刷错误:您必须写 java.lang.Long得到盒装类型!

另一方面,您需要注意 IntArrayArray<Int> 更有效(对应于 Java int[]java.lang.Integer[] ) 尽管两者似乎都使用 Int.