hi guys, I have a performance question to ask. I’m...
# getting-started
a
hi guys, I have a performance question to ask. I’m working with IntArray (for efficiency) but then at some point I want to convert that to a list. I can use
.toList()
method no problem but then when I check for efficiency the blame graph tells me that tolist() is not that efficient. Anything I’m missing? Any suggestion?
n
.toList()
create new list object with all of your int references each call.
.toList()
core :
Copy code
/**
 * Returns a [List] containing all elements.
 */
public fun <T> Iterable<T>.toList(): List<T> {
    if (this is Collection) {
        return when (size) {
            0 -> emptyList()
            1 -> listOf(if (this is List) get(0) else iterator().next())
            else -> this.toMutableList()
        }
    }
    return this.toMutableList().optimizeReadOnlyList()
}
toMutableList()
core :
Copy code
/**
 * Returns a new [MutableList] filled with all elements of this collection.
 */
public fun <T> Iterable<T>.toMutableList(): MutableList<T> {
    if (this is Collection<T>)
        return this.toMutableList()
    return toCollection(ArrayList<T>())
}
IntArray is not collection and it’s `toCollection()`call :
Copy code
/**
 * Appends all elements to the given [destination] collection.
 */
public fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection(destination: C): C {
    for (item in this) {
        destination.add(item)
    }
    return destination
}
a
@Nicolas Chaduc so you’re suggesting to use toCollection instead?
n
if you like not call
for
loop you need to use IntArray iterator directly I think and not convert it
a
Why do you want to convert your IntArray to a list?
e
.toList()
creates a copy, while
.asList()
creates a wrapper (if that makes a difference to you)
🙏 1
a
want to convert to a list because the api returns a list not an array
a
@elizarov i remember you mentioning some pretty important distinction between list and arrays and which should be preferred in the general case
e
Prefer lists.
👍 2
a
Aren't lists less cpu-cache friendly compared to arrays?
n
arraylists are backed by arrays 🙂 but I wonder if you call IntArray.asList, if it'll autobox everything you get out of it...probably. not much you can do about that.
a
asList did the trick since it’s baked by the array and doesn’t require copy