What operations are performed in bulk when using parallel collections? Strange behavior here

Enter the following small sequential program and its parallel version in the 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)}}

Performing X with X.main(Array.empty)gives:

1
2
3
4
5
6
7
8
9
10
[total 10002ms]

While 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 options for 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(_)}}

Give me battery life and accordingly. How can it be? [total 1002ms] [total 1002ms]

+5
source share
2 answers

. . , AST ( -Xprint:typer):

for (x <- (1 to 10)) {Thread.sleep(1000);println(x)}

scala.this.Predef.intWrapper(1).to(10).foreach[Unit](((x: Int) => {
  java.this.lang.Thread.sleep(1000L);
  scala.this.Predef.println(x)
}))

(1 to 10).foreach{Thread.sleep(1000);println(_)}

scala.this.Predef.intWrapper(1).to(10).foreach[Unit]({
  java.this.lang.Thread.sleep(1000L);
  ((x$1: Int) => scala.this.Predef.println(x$1))
})

. , foreach

(1 to 10).foreach{x => Thread.sleep(1000);println(x)}

? foreach, . foreach, , .

. . , .

+7

, , scala - ( Scala, ), {Thread.sleep(1000); println()} , {Thread.sleep(1000); println()} println (_) foreach, foreach (x = > Thread.sleep(1000); println (x)), Thread.sleep(1000), println (x) foreach. , sschaef.

0

All Articles