Say I have a list of size 30k elements, and I would like to perform an operation on all possible pairs within a list. So I had:
list.asSequence().flatMap { i ->
list.asSequence().map { j -> /* perform operation here */ }
}
Question 1: Is there anything that I can use as an alternative? (Such as applicative functors).
I also noticed that this flatMap-map operation is significantly slower than the imperative loop version. (perhaps due to closures?)
for(i in list){
for(j in list){
}
}
Question 2: Is there a way to improve the performance of the flatMap/map version?
Some alternatives with performance impacts:
flatMap
/map
solution. :-(forEach
/forEach
: As you simply want to perform an operation on each pair then you don't actually need to use flatMap
or map
to transform the list so you can use forEach
/forEach
instead:
list.forEach { i ->
list.forEach { j -> /* perform operation here */ }
}
for
/for
solution. :-)If you do need to transform the list then your flatMap
/map
solutions appears to be the best solution.
Answering to the question 2, we're considering to add flatMap
overload which doesn't create closures for each element in the outer collection/sequence: https://youtrack.jetbrains.com/issue/KT-8602
But in case if you want to perform some side effects on each pair, rather than transforming the sequence, I'd advice to stick with for
-loops or inlined forEach
lambdas, which is effectively the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With