7

I am a Scala beginner, practicing my FP skills with Project Euler.

While working on "Problem 5: What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20", I was comparing Range- vs. Stream-based solutions:

val r1 = Range(20, Int.MaxValue).find(i => (2 to 20).forall(i % _ == 0)).get
val r2 = Stream.from(20).find(i => (2 to 20).forall(i % _ == 0)).get

Strangely, the computation of r1 finishes in roughly 20 seconds, while the Stream-based calculation of r2 is running out of memory. I would have expected the opposite -- could anyone explain please?

Rahel Lüthy
  • 6,837
  • 3
  • 36
  • 51
  • Try Iterator instead of Stream. Also, check out this question for how to get better performance: http://stackoverflow.com/q/6146182/770361 – Luigi Plinge Nov 05 '12 at 05:52

1 Answers1

7

For range it always takes fixed size of memory.

For stream it will cache all the element you are even used. So during find stream in r2 is keep increase until out of memory.

Tim Green
  • 3,571
  • 2
  • 23
  • 23