Hello! Asking myself, how expensive a toMutableLis...
# general-advice
e
Hello! Asking myself, how expensive a toMutableList() actually is. Looked down the implementation, in the end goes for toArray() which will do a copy using the system (C) based implementation using System.arraycopy. But in the end, the actual elements are, AFAICS, not copied but assigned by ref. So i see that it is a O(n) runtime, but it will not copy the actual values (space) but use the ref - maybe even better depending of possible pointer arr in System.arraycopy. Even though i found https://slack-chats.kotlinlang.org/t/455570/how-expensive-is-mutablelist-tolist-is-it-just-basically-a-t i would love to have a more technical answer to that. Motivation: Due java op, we get a List and have no idea if it is mutable or not, but we want to have a mutable list. Usually (currently), it already is a mutable list, but it might change. So we though about using toMutableList 'to ensure it'.
k
All of the library methods that copy an array or collection only do shallow copies. The methods wouldn't know how to deep-copy, since that would require knowledge of what is being copied. You might consider something like this:
Copy code
val mutableList = (returnedList as? MutableList) ?: returnedList.toMutableList()
so that you only make the copy if the list is not already mutable. But if this list comes from Java and is wrapped in
Collections.unmodifiableList
then this unmodifiableList will still be seen as a
MutableList
in Kotlin but you will get an exception at runtime if you try to modify it. In any case, are you sure that the returned list is safe to modify? Are there any risks related to multithreading? Does the Java side that returned that list to you not want the contents of that list any more? Given such considerations, the Java method that returns the list needs to specify whether it's safe to modify that list or not - in which case, you won't have this problem any more.