没有任何惩罚(事实上,由于没有装箱,它会更快),但是,与 Java 中的基本类型一样,如果您希望能够将某些方法与[Int/Double/etc]Array
.
这实际上已经在 Kotlin 论坛上讨论过 https://discuss.kotlinlang.org/t/why-do-the-primitive-array-classes-need-to-be-exposed/1455:
整数数组的内存布局与对象指针数组的内存布局有很大不同。
Norswap 在该讨论中的评论很好地总结了这种权衡:
The native one [int[]
/IntArray
] is faster to read/write, but the wrapped [Integer[]
/Array<Int>
] does not need to be entirely converted each time it crosses a generic boundary.
#7, norswap https://discuss.kotlinlang.org/t/why-do-the-primitive-array-classes-need-to-be-exposed/1455/7
例如,一个函数接受Array<Int>
(Integer[]
在 JVM 上)将not接受一个IntArray
(int[]
).
您已经列出了唯一真正的区别,即编译为原始类型double[]
另一个到Double[]
。然而,Double[]
是一个数组objects,因此每当您通过将值设置为 a 来修改数组时double
,或检索一个double
,将分别进行装箱和拆箱。
通常建议使用DoubleArray
相反,出于速度和内存的原因。
作为由于对象包装器造成的速度损失的示例,请看一下开头this https://stackoverflow.com/a/5199425/7366707帖子,摘自《Effective Java》:
public static void main(String[] args) {
Long sum = 0L; // uses Long, not long
for (long i = 0; i <= Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);
}
更换Long
with long
将运行时间从 43 秒缩短至 8 秒。