我正在创建一个值列表,在这种情况下,尽管每次一次添加一个值,但最终的数字是事先知道的。该函数将被多次调用,因此它运行得越快越好。
在Java中,我将使用ArrayList构造函数来指定初始容量,因为从理论上讲,这会使其稍快一些,因为它避免了调整大小。
在Kotlin中,通常使用mutableListOf(),但这不允许初始容量;从理论上讲,这应该会导致代码变慢。
在这种情况下,是推荐的/惯用的Kotlin解决方案:
mutableListOf不允许默认容量的原因之一是因为kotlin中的默认值不为null。
但是在kotlin.collections
程序包中有实用程序功能defined。
public inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
val list = ArrayList<T>(size)
repeat(size) { index -> list.add(init(index)) }
return list
}
您可以使用List功能或MutableList功能创建具有默认容量及其映射的列表。
// creates a list of ints with default capacity of 10 and having nulls.
// But I highly doubt you should initialize it with a null since Kotlin is a null-safe language.
val list = MutableList<Int?>(10) { null }