If I'm recursively creating elements of an Array, ...
# getting-started
y
If I'm recursively creating elements of an Array, and I know the maximum size of that array, is there a reason ever to create my own
data class AppendableArray<T>(array: Array<T>, freeIndex: Int)
? Or is that close enough in performance to a List, and so a List makes more sense because of ergonomics? In other words, I'm creating a List of exactly size N, but I'm adding the elements recursively, and so I'm not really building them based on the index. Is an Array + lastIndex "better" in any way, or is a List with initial capacity close enough in performance
j
I'm not sure I entirely get what your goal is, but you can definitely create a mutable list with a custom initial capacity (so it doesn't need to grow).
I guess your edit makes my comment redundant 😅
y
Yes so if I have a list with the needed initial capacity, are there any inefficiencies in ArrayList that can arise then? Or is an ArrayList that never ends up growing just simply an Array + index (I know they'd be semantically the same, but are they approximately of the same performance)
j
My honest answer is I don't know, it would be interesting to measure. That said, an
ArrayList
is technically a wrapper over an array+index, that replaces the array with a bigger one when needed. If you tune the initial capacity so it never resizes the array, I don't believe there should be a significant performance difference when writing data. There could be some subtleties related to indirections of using the list wrapper to edit the array (e.g. memory locality), but I'm not sure this would have a noticeable impact on perf (also if you write your own wrapper, you have the same problem). One big difference of course would be using
List<Int>
vs
IntArray
, but that only applies to primitives.
y
More concretely, I was creating a list of all permutations of an IntArray, and I was wondering if having an
ArrayList<IntArray>
Vs
Array<IntArray> + some mutable index
would matter too much. This was a purely academic exercise, so my question is entirely theoretical.
e
java.util.ArrayList
contains fields
Object[] data
,
int size
, and
int modCount
from its superclass
AbstractList
kotlin.collections.ArrayList
is basically an alias on JVM
j
I was wondering if having an ArrayList<IntArray> Vs Array<IntArray> + some mutable index would matter too much
If you compare
ArrayList
to your wrapper class (and not to the direct usage of the array itself), then it's pretty much the same
k
One very minor performance overhead is that every time you add an element to an
ArrayList
it would check its capacity, which your custom class wouldn't do because it already knows it has the capacity. But I don't think you'd be able to measure that difference.