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:

我还注意到,这个flatMap-map操作比命令式循环版本要慢得多.(可能是因为关闭?)

for(i in list){
    for(j in list){

    }
}

Question 2:有没有办法提高flatMap/map版本的性能?

推荐答案

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.

Kotlin相关问答推荐

如何在使用Kotlin Coroutines时检测和记录何时出现背压

用浮点数或十进制数给出错误答案的阶乘计算

在intellij中使用kotlin符号和floordiv

捕捉异常是Kotlin协程中的反模式吗?

为什么不';Kotlin是否在数据类构造函数中隐式分配null值可为null的字段?

Gradle:无法创建 ExtensiblePolymorphicDomainObjectContainer

如何将 `when` 与 2 个密封类一起使用并获取内部值?

使用 kotlin 流删除 map 中具有某些相似性的值

Kotlin 如何使用其 get 函数在内部检索映射值

如何使用子变量在 Kotlin 中初始化父级

在 Kotlin 协程中切换 IO 和 UI 的正确方法是什么?

为什么没有remember 的 mutableStateOf 有时会起作用?

API 'variant.getJavaCompile()' 已过时

在 Koin 中提供一个 Instance 作为其接口

Kotlin默认使用哪种排序?

launch 仅从 Kotlin 1.3 开始可用,不能在 Kotlin 1.2 中使用

如何在使用Koin DI的活动之间共享同一个ViewModel实例?

使用 kotlin 每 3 位数添加逗号或点

Android room DAO 接口不适用于继承

Dagger 2 androidx fragment不兼容类型