有趣的 Kotlin 0x0D: IntArray vs Array<Int>

642 阅读1分钟

介绍

IntArray

整数数组。在 JVM 平台上,对应 int[]

Array

Array<T> 表示 T 类型数组。在 JVM 平台上,Array<Int> 对应 Integer[]

验证

fun main() {
    val one = IntArray(10) { it }
    val two = Array<Int>(10) { it }
}

Decompile

Java Code

综上,JVM 平台上,IntArrayArray<Int> 的区别在于对应的类型不同,一个是基础类型 int 数组,另外一个是封装类型 Integer 数组,有装箱开销

开销差距

一般情况下,看不出差距,只能用放大镜看一下了。

@OptIn(ExperimentalTime::class)
fun main() {
​
    val duration1 = measureTime {
        case1()
    }
    println(duration1)
​
    val duration2 = measureTime {
        case2()
    }
    println(duration2)
}
​
private fun case1() {
    val t = IntArray(10_000_000)
}
​
private fun case2() {
    val t = Array<Int>(10_000_000) { it }
}

运行结果

使用场景

  • 默认使用 IntArray,基础类型因无装箱开销而性能好,且每个元素都有默认值 0
  • 如果数组需要使用 null 值,使用 Array<Int>

StackOverflow

高赞回答,一言以蔽之。

StackOverflow Issues

\