Input the following little sequential program and its parallelized version in Scala REPL:
/* Activate time measurement in "App" class. Prints [total <X> ms] on exit. */
util.Properties.setProp("scala.time", "true")
/* Define sequential program version. */
object X extends App { for (x <- (1 to 10)) {Thread.sleep(1000);println(x)}}
/* Define parallel program version. Note '.par' selector on Range here. */
object Y extends App { for (y <- (1 to 10).par) {Thread.sleep(1000);println(y)}}
Executing X with X.main(Array.empty)
gives:
1
2
3
4
5
6
7
8
9
10
[total 10002ms]
Whereas Y with Y.main(Array.empty)
gives:
1
6
2
7
3
8
4
9
10
5
[total 5002ms]
So far so good. But what about the following two variations of the program:
object X extends App {(1 to 10).foreach{Thread.sleep(1000);println(_)}}
object Y extends App {(1 to 10).par.foreach{Thread.sleep(1000);println(_)}}
The give me runtimes of [total 1002ms]
and [total 1002ms]
respectively. How can this be?