gpt4 book ai didi

kotlin - 筛选、减法或分组依据——什么是最有效的? ( Kotlin )

转载 作者:行者123 更新时间:2023-12-01 13:20:00 26 4
gpt4 key购买 nike

例如,我们有一个列表,我们想用特定的谓词将其分成两部分。

首先,我们可以使用filterfilterNot

val trueList = list.filter(predicate)
val falseList = list.filterNot(predicate)

其次,我们可以使用filtersubtract:

val trueList = list.filter(predicate)
val falseList = list.subtract(trueList)

第三,我们可以使用groupBy:

val groupBy = list.groupBy(predicate)
val trueList = groupBy[true]
val falseList = groupBy[false]

什么是最有效、最快的方法?我们可以用其他一些功能来做到这一点吗?

我认为带有 subtract 的第二种选择是最糟糕的,对吗?

最佳答案

因此,我试图了解哪个选项最快:filtersubtractgroupBypartition (感谢 Marko Topolnik 的提示)。我使用 measureTimeMillis 来了解每个选项的运行时间:

private fun checkTime(list: List<Int>, predicate: (Int) -> Boolean) {
var sum = 0L
repeat(times) { sum += checkPartition(list, predicate) }
println("partition: ${sum/times}")

sum = 0L
repeat(times) { sum += checkFilter(list, predicate) }
println("filter: ${sum/times}")

sum = 0L
repeat(times) { sum += checkSubtract(list, predicate) }
println("subtract: ${sum/times}")

sum = 0L
repeat(times) { sum += checkGroupBy(list, predicate) }
println("group by: ${sum/times}")
}


private fun checkGroupBy(list: List<Int>, predicate: (Int) -> Boolean): Long {
return measureTimeMillis {
val groupBy = list.groupBy(predicate)
val falseList = groupBy[false]
val trueList = groupBy[true]
}
}

private fun checkSubtract(list: List<Int>, predicate: (Int) -> Boolean): Long {
return measureTimeMillis {
val trueList = list.filter(predicate)
val falseList = list.subtract(trueList)
}
}

private fun checkFilter(list: List<Int>, predicate: (Int) -> Boolean): Long {
return measureTimeMillis {
val trueList = list.filter(predicate)
val falseList = list.filterNot(predicate)
}
}

private fun checkPartition(list: List<Int>, predicate: (Int) -> Boolean): Long {
return measureTimeMillis {
val pair = list.partition(predicate)
val trueList = pair.first
val falseList = pair.second
}
}

我重复检查了 10 次,这个谓词:

val predicate = { it: Int -> it % 2 == 0 }

以及具有不同大小的列表:

var list = (1..1_000_000).toList()
checkTime(list, predicate)

partition: 16 filter: 21 subtract: 81 group by: 18

list = (1..2_000_000).toList()
checkTime(list, predicate)

partition: 30 filter: 42 subtract: 241 group by: 36

list = (1..3_000_000).toList()
checkTime(list, predicate)

partition: 35 filter: 59 subtract: 233 group by: 63

所以,partition将列表分成两部分是一个非常好的选择。

请告诉我,如果我做错了什么。

关于kotlin - 筛选、减法或分组依据——什么是最有效的? ( Kotlin ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50392391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com