【问题标题】:Converting collections performance转换集合性能
【发布时间】:2017-04-17 01:28:26
【问题描述】:

在我的代码中,我使用不同类型的集合,并且经常将一个集合转换为另一个集合。我可以轻松调用toListtoVectortoSettoArray 函数。

现在我对执行此操作很感兴趣。我在documentation 中找到有关lengthheadtailapply 性能的信息。当我在 scala 中调用 ListSetArrayVector 上的函数(toListtoVectortoSettoArray)时实际发生了什么?

附:问题只是关于不可变的标准 scala 集合。

【问题讨论】:

  • 如果您乐于阅读 scala 源代码:github.com/scala/scala/tree/2.12.x/src/library/scala/collection
  • @Pavel 我试着读它我看不懂,一个好的解释会很好,你不这么认为吗?每个人都可以google这个问题,并得到基本的想法,不是很好吗?
  • 如果您不了解任何特定的代码段,您可以随时更新您的答案以提供更多详细信息。这里有足够的人愿意提供帮助。请更具体。谢谢

标签: performance scala collections immutability


【解决方案1】:

我的建议是:查看源代码!例如,方法 toSet 在 TraversableOnce 特征中定义如下(由我自己注释):

  def to[Col[_]](implicit cbf: CanBuildFrom[Nothing, A, Col[A @uV]]): Col[A @uV] = {
    val b = cbf() //generic way to build the collection, if it would be a List, it would create an empty List
    b ++= seq // add all the elements
    b.result() //transform the result to the target collection
  }

所以这意味着 toSet 方法的性能为 O(N),因为您遍历了所有列表一次!我相信所有继承这个 trait 的集合都在使用这个实现。

【讨论】:

  • 不完全...如果插入到集合中需要恒定的时间,那么您是正确的。所以要完整:需要O(n * <time taken to insert 1 element>)。因此,如果使用 BST 实现 Set,则 toSet 函数将为 O(n log(n))
猜你喜欢
  • 2013-10-20
  • 1970-01-01
  • 2020-03-20
  • 2017-11-28
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多