https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Andrea Giuliano

12/09/2020, 1:06 PM
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

Nicolas Chaduc

12/09/2020, 1:17 PM
.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

Andrea Giuliano

12/09/2020, 1:18 PM
@Nicolas Chaduc so you’re suggesting to use toCollection instead?
n

Nicolas Chaduc

12/09/2020, 1:20 PM
if you like not call
for
loop you need to use IntArray iterator directly I think and not convert it
a

Adam Powell

12/09/2020, 2:19 PM
Why do you want to convert your IntArray to a list?
e

ephemient

12/09/2020, 2:30 PM
.toList()
creates a copy, while
.asList()
creates a wrapper (if that makes a difference to you)
🙏 1
a

Andrea Giuliano

12/09/2020, 3:20 PM
want to convert to a list because the api returns a list not an array
a

asad.awadia

12/09/2020, 4:53 PM
@elizarov i remember you mentioning some pretty important distinction between list and arrays and which should be preferred in the general case
e

elizarov

12/09/2020, 4:53 PM
Prefer lists.
👍 2
a

asad.awadia

12/09/2020, 4:54 PM
Aren't lists less cpu-cache friendly compared to arrays?
n

nanodeath

12/09/2020, 5:15 PM
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

Andrea Giuliano

12/12/2020, 5:22 PM
asList did the trick since it’s baked by the array and doesn’t require copy
2 Views