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))
The returning value The first difference between map() and forEach() is the returning value. The forEach() method returns undefined and map() returns a new array with the transformed elements. Even if they do the same job, the returning value remains different.
There seems to be a very small difference between forEach() and map() with respect to speed. map() is faster, but these are so miniscule that it shouldn't affect your application's performance significantly. You can almost always use map() and other array methods like filter() and reduce() instead of using forEach().
The important difference between them is that map accumulates all of the results into a collection, whereas foreach returns nothing. map is usually used when you want to transform a collection of elements with a function, whereas foreach simply executes an action for each element.
1) forEach method After executing the function for every array element, this method changes the values of the existing array elements according to the result of the provided function. Hence forEach() is a mutator method. Also, forEach method doesn't return anything (undefined).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With