Skip to content
Browse files

SI-2818 Make List.foldRight always do a reverse/foldLeft flip

Benchmarks show that lists smaller than 110 elements or so doing
reverse/foldLeft is faster than recursively walking to the end of
the list and then folding as the stack unwinds.

Above that 110 element threshold the recursive procedure is faster.
Unfortunately, at some magic unknown large size the recursive procedure
blows the stack.

This commit changes List#foldRight to always do reverse/foldLeft.
  • Loading branch information...
1 parent 7026376 commit 6db4db93a7d976f1a3b99f8f1bffff23a1ae3924 @JamesIry JamesIry committed Jan 30, 2013
Showing with 13 additions and 0 deletions.
  1. +3 −0 src/library/scala/collection/immutable/List.scala
  2. +4 −0 test/files/run/t2818.check
  3. +6 −0 test/files/run/t2818.scala
View
3 src/library/scala/collection/immutable/List.scala
@@ -295,6 +295,9 @@ sealed abstract class List[+A] extends AbstractSeq[A]
}
result
}
+
+ override def foldRight[B](z: B)(op: (A, B) => B): B =
+ reverse.foldLeft(z)((right, left) => op(left, right))
override def stringPrefix = "List"
View
4 test/files/run/t2818.check
@@ -0,0 +1,4 @@
+105
+499999500000
+0
+1
View
6 test/files/run/t2818.scala
@@ -0,0 +1,6 @@
+object Test extends App {
+ println((List.range(1L, 15L) :\ 0L) (_ + _))
+ println((List.range(1L, 1000000L) :\ 0L) (_ + _))
+ println((List.fill(5)(1) :\ 1) (_ - _))
+ println((List.fill(1000000)(1) :\ 1) (_ - _))
+}

1 comment on commit 6db4db9

@xuwei-k

Is there any reason does not override List#reduceRight in the same way as foldRight?

Please sign in to comment.
Something went wrong with that request. Please try again.