I want to make some optimzation to foldLeft using in-memmory functions using some collections Considering the following Code:
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)
}
}
- Does each time that result is aggregated with
List
, the whole collection is copied? - Does :+ on Seq copying to new Seq or just appended element in the end? probably - O(1)?
- Does :+ on List copying to new List or just appending element in the end? probably - O(n)?
- Does mutableList is faster then foldLeft with List since there no copying on each aggregation?
- Do you recommend to foldLeft in another way for better performance? Thanks!