Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

arraylist - 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.

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.

In Kotlin, one normally uses mutableListOf(), but this does not allow an initial capacity; in theory this should result in slightly slower code.

Is the recommended/idiomatic Kotlin solution in this case:

  1. Go ahead and use the ArrayList constructor; ArrayList is a perfectly valid MutableList.
  2. Ignore the issue; the initial capacity never actually makes a measurable difference to speed.
  3. Something else?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updated Answer

I was actually confused with capacity and size. There is no implementation of using a default capacity MutableList currently in Kotlin stdlib.

You can make one yourself.

fun <T> mutableListWithCapacity(capacity: Int): MutableList<T> =
    ArrayList(capacity)

// creates a MutableList of Int with capacity of 5.
val mutableList = mutableListWithCapacity<Int>(5)

Outdated Answer

One of the reason why mutableListOf does not allow for default capacity is because default values in kotlin is not null.

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
}

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 }

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 ?. !!..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...