Skip to content

Commit

Permalink
Chunk - Optimise Flatten implementation.
Browse files Browse the repository at this point in the history
The current flatten performs one Chunk.Queue insertion
per source chunk, which means it creates a new
"Chunk.Queue" object and one "Queue" object for each one.
Instead, we can avoid those objects and use a Queue- builder.
  • Loading branch information
diesalbla committed Mar 26, 2023
1 parent 897c3b8 commit f5a4d11
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions core/shared/src/main/scala/fs2/Chunk.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1007,7 +1007,8 @@ object Chunk
*
* This is similar to a queue of individual elements but chunk structure is maintained.
*/
final class Queue[+O] private (val chunks: SQueue[Chunk[O]], val size: Int) extends Chunk[O] {
final class Queue[+O] private[Chunk] (val chunks: SQueue[Chunk[O]], val size: Int)
extends Chunk[O] {

private[this] lazy val accumulatedLengths: (Array[Int], Array[Chunk[O]]) = {
val lens = new Array[Int](chunks.size)
Expand Down Expand Up @@ -1221,9 +1222,15 @@ object Chunk
if (ffa.isEmpty) Chunk.empty
else if (ffa.size == 1) ffa(0) // short-circuit and simply return the first chunk
else {
var acc = Chunk.Queue.empty[A]
ffa.foreach(x => acc = acc :+ x)
acc
val sqb = SQueue.newBuilder[Chunk[A]]
var totalSize = 0
ffa.foreach { (ch: Chunk[A]) =>
if (!ch.isEmpty) {
sqb += ch
totalSize += ch.size
}
}
new Chunk.Queue[A](sqb.result(), totalSize)
}

override def traverse_[F[_], A, B](
Expand Down

0 comments on commit f5a4d11

Please sign in to comment.