From e3ddb2d7dff859c9fb81d34d1c9687f72321a713 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 26 Mar 2013 23:50:50 -0700 Subject: Iterator.++ no longer blows the stack. To my chagrin we still hadn't gotten this one. I took a new approach which seems like a winner to me. Here's a benchmark: object Test { def run(n: Int) = println((1 to n).foldLeft(Iterator.empty: Iterator[Int])((res, _) => res ++ Iterator(1)) sum) def main(args: Array[String]): Unit = run(args(0).toInt) } Runtime before this commit for various n: 500 0.403 real 1000 0.911 real 1500 2.351 real 2000 5.298 real 2500 10.184 real Runtime after this commit, same n: 500 0.346 real 1000 0.359 real 1500 0.368 real 2000 0.379 real 2500 0.390 real In the test case I dial it up to 100000. --- test/files/run/iterator-concat.scala | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 test/files/run/iterator-concat.scala (limited to 'test/files/run/iterator-concat.scala') diff --git a/test/files/run/iterator-concat.scala b/test/files/run/iterator-concat.scala new file mode 100644 index 0000000000..f11363410f --- /dev/null +++ b/test/files/run/iterator-concat.scala @@ -0,0 +1,15 @@ +object Test { + // Create `size` Function0s, each of which evaluates to an Iterator + // which produces 1. Then fold them over ++ to get a single iterator, + // which should sum to "size". + def mk(size: Int): Iterator[Int] = { + val closures = (1 to size).toList.map(x => (() => Iterator(1))) + closures.foldLeft(Iterator.empty: Iterator[Int])((res, f) => res ++ f()) + } + def main(args: Array[String]): Unit = { + println(mk(100).sum) + println(mk(1000).sum) + println(mk(10000).sum) + println(mk(100000).sum) + } +} -- cgit v1.2.3