I have a question / idea about sequences, by defau...
# language-evolution
d
I have a question / idea about sequences, by default and by design, sequences are unbounded (or rather their size is unknown upfront), this could lead to a final step such as
toList
creating a list that needs to be resized a couple of times to accommodate more and more items. If I'm not mistaken, the implementation for
toList
is:
Copy code
public fun <T> Sequence<T>.toList(): List<T> {
    val it = iterator()
    if (!it.hasNext())
        return emptyList()
    val element = it.next()
    if (!it.hasNext())
        return listOf(element)
    val dst = ArrayList<T>()
    dst.add(element)
    while (it.hasNext()) dst.add(it.next())
    return dst
}
Here you can see it creates an
ArrayList
and keeps adding the next element. Would it be useful / make sense to have a specialization of sequence, such as
BoundedSequence
where the number of elements is known in advance so it can be carried over to the last operator to avoid creating multiple collections?
2
k
It sounds reasonable to me. As a workaround in the meantime, if you have the size of the sequence in a separate variable (instead of it being a property of the BoundedSequence) you can do
sequence.toCollection(ArrayList(size))
.
h
How do you know the size of the final sequence when you filter elements or add elements using flatMap?
d
When you filter, it could become smaller, so maybe it's okay-ish to still have the original size, there will be some memory overhead, but that's also the case in the current implementation. With flatMap, it might be okay to use the initial size as the initial size of the resulting collection as well, but still allow resizing if needed?