问题描述
这个 SO 答案 描述了如何使用 scala.collection.breakOut
来防止创建浪费的中间集合.比如这里我们创建一个中间的Seq[(String,String)]
:
This SO answer describes how scala.collection.breakOut
can be used to prevent creating wasteful intermediate collections. For example, here we create an intermediate Seq[(String,String)]
:
val m = List("A", "B", "C").map(x => x -> x).toMap
通过使用breakOut
,我们可以防止创建这个中间Seq
:
By using breakOut
we can prevent the creation of this intermediate Seq
:
val m: Map[String,String] = List("A", "B", "C").map(x => x -> x)(breakOut)
视图解决了同样的问题,此外惰性访问元素:
val m = (List("A", "B", "C").view map (x => x -> x)).toMap
我假设 View
包装器的创建相当便宜,所以我的问题是:是否有任何真正的理由使用 breakOut
而不是 View代码>s?
I am assuming the creation of the View
wrappers is fairly cheap, so my question is: Is there any real reason to use breakOut
over View
s?
推荐答案
从 Scala 2.13 开始,这不再是一个问题.Breakout 已被移除,建议替换为视图.
As of Scala 2.13, this is no longer a concern. Breakout has been removed and views are the recommended replacement.
视图也是 collection.breakOut 的推荐替代品.例如,
val s: Seq[Int] = ...
val set: Set[String] = s.map(_.toString)(collection.breakOut)
可以用与以下相同的性能特征表示:
val s: Seq[Int] = ...
val set = s.view.map(_.toString).to(Set)
这篇关于scala.collection.breakOut 与视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!