Kotlin MutableList的初始容量 [英] Kotlin MutableList initial capacity
问题描述
我正在创建一个值列表,在这种情况下,尽管每次一次添加一个值,但最终的数字是事先知道的.该函数会被多次调用,因此它运行得越快越好.
I'm creating a list of values, in a context where it so happens that, though the values are being added one at a time, the eventual number is known in advance. This is in a function that will be called many times, so the faster it runs, the better.
在Java中,我将使用ArrayList构造函数来指定初始容量,因为从理论上讲,这会使其稍快一些,因为它避免了调整大小.
In Java, I would use the ArrayList constructor that specifies an initial capacity, because in theory this makes it slightly faster because it avoids resizing.
在Kotlin中,通常使用mutableListOf(),但这不允许初始容量.从理论上讲,这应该会导致代码变慢.
In Kotlin, one normally uses mutableListOf(), but this does not allow an initial capacity; in theory this should result in slightly slower code.
在这种情况下,是推荐的/惯用的Kotlin解决方案:
Is the recommended/idiomatic Kotlin solution in this case:
- 继续使用ArrayList构造函数; ArrayList是一个完全有效的MutableList.
- 忽略该问题;初始容量实际上不会对速度产生明显的影响.
- 还有别的吗?
推荐答案
更新后的答案
我实际上对容量和大小感到困惑. Kotlin stdlib当前没有使用默认容量MutableList的实现.
Updated Answer
I was actually confused with capacity and size. There is no implementation of using a default capacity MutableList currently in Kotlin stdlib.
你可以自己做.
fun <T> mutableListWithCapacity(capacity: Int): MutableList<T> =
ArrayList(capacity)
// creates a MutableList of Int with capacity of 5.
val mutableList = mutableListWithCapacity<Int>(5)
过时的答案
mutableListOf <的原因之一/a>不允许使用默认容量是因为kotlin中的默认值不为空.
Outdated Answer
One of the reason why mutableListOf does not allow for default capacity is because default values in kotlin is not null.
但是kotlin.collections
软件包中有已定义的实用程序功能.
However there is a utility function defined in kotlin.collections
package.
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
}
您可以使用列表函数或 MutableList 函数与默认容量及其映射.
You can create a List with a List function or MutableList function with a default capacity and its mapping.
// 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 }
但是,如果要使用非空列表,则Kotlin中不应有空值,否则您必须使用?.
!!.
之类的运算符进行空值检查.
But since there should not be nulls in Kotlin if it is intended use of non-null list else you have to do a null check using operators like ?.
!!.
.
这篇关于Kotlin MutableList的初始容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!