Skip to content

Commit

Permalink
Experiment: use immutable List for optimized traverse
Browse files Browse the repository at this point in the history
To see if this is more performant than an immutable vector
  • Loading branch information
TimWSpence committed Nov 10, 2023
1 parent 8cc742e commit e3ae584
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 6 deletions.
8 changes: 4 additions & 4 deletions core/src/main/scala/cats/Traverse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -287,14 +287,14 @@ object Traverse {

private[cats] def traverseDirectly[G[_], A, B](
fa: IterableOnce[A]
)(f: A => G[B])(implicit G: StackSafeMonad[G]): G[Vector[B]] = {
fa.iterator.foldLeft(G.pure(Vector.empty[B])) { case (accG, a) =>
)(f: A => G[B])(implicit G: StackSafeMonad[G]): G[List[B]] = {
G.map(fa.iterator.foldLeft(G.pure(List.empty[B])) { case (accG, a) =>
G.flatMap(accG) { acc =>
G.map(f(a)) { b =>
acc :+ b
b :: acc
}
}
}
})(_.reverse)
}

private[cats] def traverse_Directly[G[_], A, B](
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/scala/cats/instances/list.scala
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ trait ListInstances extends cats.kernel.instances.ListInstances {
if (fa.isEmpty) G.pure(Nil)
else
G match {
case x: StackSafeMonad[G] => G.map(Traverse.traverseDirectly[G, A, B](fa)(f)(x))(_.toList)
case x: StackSafeMonad[G] => Traverse.traverseDirectly[G, A, B](fa)(f)(x)
case _ =>
G.map(Chain.traverseViaChain {
val as = collection.mutable.ArrayBuffer[A]()
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/scala/cats/instances/vector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ trait VectorInstances extends cats.kernel.instances.VectorInstances {

final override def traverse[G[_], A, B](fa: Vector[A])(f: A => G[B])(implicit G: Applicative[G]): G[Vector[B]] =
G match {
case x: StackSafeMonad[G] => Traverse.traverseDirectly(fa)(f)(x)
case x: StackSafeMonad[G] => x.map(Traverse.traverseDirectly(fa)(f)(x))(_.toVector)
case _ => G.map(Chain.traverseViaChain(fa)(f))(_.toVector)
}

Expand Down

0 comments on commit e3ae584

Please sign in to comment.