Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can reduceLeft be executed in parallel?

Tags:

scala

I just started learning Scala, so please be patient :-)

I have a question about how reduceLeft behaves. Here an example:

List(1, 2, 3, 4, 5) reduceLeft (_ + _)

I wonder if the calculation can be done simultanously, e.g.:

first round:

  • process 1 calculates: 1 + 2
  • process 2 calculates: 4 + 5

second round:

  • process 1 calculates: 3 + 3

third round:

  • process 1 calculates: 6 + 9

At least that's what I would expect to happen if I just use the reduce function instead of reduceLeft. Or does reduceLeft really only does one reduction at a time?

((((1 + 2) + 3) + 4) + 5)

This would basically mean it can't be executed in parallel and one should always prefer reduce over reduceLeft/Right if possible?

like image 269
Sebi Avatar asked Mar 07 '13 22:03

Sebi


1 Answers

The answer is yes, and it is very easy:

List(1, 2, 3, 4, 5).par.reduce (_ + _)

The par method turns the list into a parallel collection. When you call reduce on this parallel collection, it will be executed in parallel.

See the parallel collection documentation

like image 187
Régis Jean-Gilles Avatar answered Sep 23 '22 20:09

Régis Jean-Gilles