Scala 中的 map 和 foreach 方法之间的区别?

编程入门 行业动态 更新时间:2024-10-16 18:40:48
本文介绍了Scala 中的 map 和 foreach 方法之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我开始编程 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 方法之间的区别?

本文发布于:2023-11-25 15:15:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630257.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   方法   Scala   map   foreach

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!