Kotlin MutableList 初始容量 [英] Kotlin MutableList initial capacity

查看:45
本文介绍了Kotlin MutableList 初始容量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个值列表,在这种情况下,尽管值一次添加一个,但最终数字是预先知道的.这是在一个会被多次调用的函数中,所以它运行得越快越好.

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:

  1. 继续使用 ArrayList 构造函数;ArrayList 是一个完全有效的 MutableList.
  2. 忽略这个问题;初始容量实际上从未对速度产生可测量的差异.
  3. 还有别的吗?

推荐答案

更新答案

我实际上对容量和大小感到困惑.目前在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆