Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between map and foreach method in Scala? [duplicate]

Tags:

scala

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))
like image 429
Kishore Karunakaran Avatar asked Jun 13 '13 06:06

Kishore Karunakaran


People also ask

What is the difference between map () and forEach ()?

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.

Which is faster forEach or map?

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().

What is difference between map and forEach in streams?

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.

Does forEach return a new array?

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).


1 Answers

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.

like image 56
gpampara Avatar answered Sep 20 '22 06:09

gpampara