2

the following code takes almost forever:

val r =(1 to 10000)
   .map(_ => Seq.fill(10000)(0.0))
   .map(_.size)
   .sum

While this is very fast:

val r =(1 to 10000)
   .map(_ => Seq.fill(10000)(0.0).size)
   .sum

Why is that? I don't quit understand in which order the statements are executed. In the first case, are first 10000 Seqs of size 10000 created, and then all those mapped to the size? Or is each Seq mapped to the size individually (and thus garbage-collected)?

1 Answer 1

2

Your assumption is correct. In the first snippet, you create 10.000 Seq instances and only after that, in a second iteration, those instances are mapped to their size. In the second snippet, there is not only no need for storing each Seq (since you are only interested in their size), but there also is no need for an additional iteration.

For the sake of clarity, let's look at it without method chaining:

val range = (1 to 10000)

val a1 = range.map(_ => Seq.fill(10000)(0.0)) // all collections are maintained in memory
val a2 = a1.map(_.size)

val b = range.map(_ => Seq.fill(10000)(0.0).size) // each collection can be thrown away asap
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.