Is foreach by-definition guaranteed to iterate the subject collection sequentially in Scala?

爱⌒轻易说出口 提交于 2020-08-01 09:42:42

问题


Is foreach by-definition guaranteed to iterate the subject collection (if it defines order) sequentially from the very first to the very last (unless accidentally interrupted) element? Aren't there any compiler optimization switches which can brake it (shuffle the sequence) or plans to make the ordinary foreach parallel in future versions?


回答1:


Foreach is guaranteed to be sequential for sequential collections (that is, the normal hierarchy, or for anything transformed by .seq). The parallel part of the collections library (which you get from a standard collection via .par or by explicitly using classes from collection.parallel) are pretty much guaranteed not to evaluate in order. If you want to be agnostic, you can use the GenX set of traits (e.g. GenSeq); these provide no guarantees either on execution order or that work will be done in parallel.




回答2:


To complement the answer by Rex, foreach at GenTraversableOnce only guarantees all elements will be iterated through, unless you interrupt it. Traits lower on the hierarchy chain may provide additional guarantees, for example:

  • TraversableOnce and descendants guarantee that only one element will be iterated through at a time (not guaranteed by GenTraversableOnce!).
  • Seq and descendants guarantee that elements will be traversed on the order they are kept in the collection.

And since you asked about parallel foreach...

scala> (1 to 10).par foreach println
4
6
1
3
2
7
5
8
9
10


来源:https://stackoverflow.com/questions/9439535/is-foreach-by-definition-guaranteed-to-iterate-the-subject-collection-sequential

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!