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

Gavin Ray

07/26/2022, 6:10 PM
Which of these is likely to perform better? I assume the
List
version but you never know, figured I'd ask others:
Copy code
fun recur(...): Sequence<*> = sequence {
    yield(...)
    getQueryRelations(innerRequest).forEach {
        yieldAll(
            recur(...)
        )
    }
}
Copy code
fun recur(...): List<*> {
    return listOf(...) + getQueryRelations(innerRequest).flatMap {
        recur(...)
    }
}
e

ephemient

07/26/2022, 6:28 PM
possibly irrelevant, but if
getQueryRelations(innerRequest)
is a
suspend fun
then your
sequence
version can't be used directly.
sequenceOf(...) + getQueryRelations(innerRequest).asSequence().flatMap { ... }
could be used though
I would tend to use
Copy code
buildList {
    add(...)
    getQueryRelations(innerRequest).flatMapTo(this) { recur(...) }
}
or
Copy code
getQueryRelations(innerRequest).flatMapTo(mutableListOf(...)) { recur(...) }
instead of your second option, to avoid one whole list copy
but the performance is likely to vary on several factors
g

Gavin Ray

07/26/2022, 7:03 PM
.flatMapTo(this)
I had never thought of that, that's pretty clever!
5 Views