Firstly, the two operations are infinitely different. map
is a transformation of the list given a function A => B
, whereas foreach
yields Unit
and is usually used for side-effects.
I would guess that foreach
is "faster" in terms of cycles needed to execute compared to map
which creates a new collection (in this case) as the result of the function. But comparing these two is really comparing apples and oranges.
map
will only be parallel if the collection on which it is invoked is a parallel collection. So in your example:
list.map(x => x)
is not parallel and is sequential, but
list.par.map(x => x)
would be parallel. There are obviously various caveats that need to be taken into account with this usage. The same parallel collection has a foreach
method as well.