【发布时间】:2021-01-13 09:15:33
【问题描述】:
我想通过一些集合使用内存中的函数对 foldLeft 进行一些优化 考虑以下代码:
val buffer = List.fill(10000)(Random.nextInt(10))
def `with list appending`() = buffer.foldLeft(List[Int](), List[Int]()) { case (_@(even, odd), currNum) => {
if (currNum % 2 == 0) (even :+ currNum, odd)
else (even, odd :+ currNum)
}
}
def `with list pre appending` = {
val (evenList,oddList) = buffer.foldLeft(List[Int](), List[Int]()) { case (_@(even, odd), currNum) => {
if (currNum % 2 == 0) (currNum :: even, odd)
else (even, currNum :: odd)
}
}
(evenList.reverse, oddList.reverse)
}
def `with seq appending` = buffer.foldLeft(Seq[Int](), Seq[Int]()) { case (_@(even, odd), currNum) => {
if (currNum % 2 == 0) (even :+ currNum, odd)
else (even, odd :+ currNum)
}
}
def `with mutable list appending` = buffer.foldLeft(mutable.MutableList[Int](), mutable.MutableList[Int]()) { case (_@(even, odd), currNum) => {
if (currNum % 2 == 0) (even :+ currNum, odd)
else (even, odd :+ currNum)
}
}
- 每次将该结果与
List聚合时,是否会复制整个集合? - Seq 上的 :+ 是复制到新的 Seq 还是最后只是附加的元素?可能 - O(1)?
- List 上的 :+ 是复制到新的 List 还是只是在最后添加元素?可能 - O(n)?
- mutableList 是否比使用 List 的 foldLeft 更快,因为每个聚合都没有复制?
- 您是否建议以其他方式 foldLeft 以获得更好的性能? 谢谢!
【问题讨论】:
-
Seq是一种抽象类型,因此性能将取决于具体类型。 -
非常感谢,所以不是 List 与 MutableList,还是有其他更快的方法?
-
如果问题是列表很大,可以考虑使用流式解决方案。
标签: scala performance