15

I do have one big doubt when I started programming Scala. I want to know how the map method in scala works. Whether it's processing sequentially or in multithreaded? And more importantly I would like to know that why map method is faster than while or foreach?

val list = List(1,2,3,45,12)
list.map(x => x)
list.foreach(x => println(x))
bronislav
  • 782
  • 7
  • 27
Kishore Karunakaran
  • 598
  • 1
  • 6
  • 16
  • 4
    How do you know `map` is faster than `foreach`? – Jatin Jun 13 '13 at 06:07
  • 5
    In fact in reality, `foreach` should be faster than `map` because internally `map` builds a `list` in above case where as `foreach` does not build. Any script shows `foreach` to be faster – Jatin Jun 13 '13 at 06:16
  • Well I tested with code and which results for(i.e. map) expressions are faster in scala compared to foreach or while, etc. – Kishore Karunakaran Jun 13 '13 at 08:47
  • @Jatin: Do you not think that `println` needs more time to be executed (because it is a syscall) than a simple object creation, which only triggers the GC (if the GC manages a large enough heap). – kiritsuku Jun 13 '13 at 10:30

1 Answers1

31

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.

gpampara
  • 11,989
  • 3
  • 27
  • 26