Scala 中的 map 和 foreach 方法之间的区别? [英] Difference between map and foreach method in Scala?
问题描述
当我开始编程 Scala 时,我确实有一个很大的疑问.我想知道 Scala 中的 map
方法是如何工作的.是顺序处理还是多线程处理?更重要的是,我想知道为什么 map
方法比 while
或 foreach
更快?
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))
推荐答案
首先,这两种操作有无限的不同.map
是给定函数 A => 的列表的转换.B
,而 foreach
产生 Unit
,通常用于副作用.
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.
我猜测 foreach
与 map
相比,在执行所需的周期方面更快",后者创建了一个新集合(在这种情况下)作为结果功能.但比较这两者其实就是比较苹果和橙子.
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
只有在调用它的集合是并行集合时才会是并行的.所以在你的例子中:
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)
应该是平行的.显然,这种用法需要考虑各种注意事项.同一个并行集合也有一个 foreach
方法.
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.
这篇关于Scala 中的 map 和 foreach 方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!