【问题标题】:Iterators concatenation performance迭代器连接性能
【发布时间】:2012-12-17 02:26:25
【问题描述】:

下面是Iterator++方法的代码:

/** Concatenates this iterator with another.
       *
       *  @param   that   the other iterator
       *  @return  a new iterator that first yields the values produced by this
       *  iterator followed by the values produced by iterator `that`.
       *  @note    Reuse: $consumesTwoAndProducesOneIterator
       *  @usecase def ++(that: => Iterator[A]): Iterator[A]
       */
      def ++[B >: A](that: => GenTraversableOnce[B]): Iterator[B] = new Iterator[B] {
        // optimize a little bit to prevent n log n behavior.
        private var cur : Iterator[B] = self
        // since that is by-name, make sure it's only referenced once -
        // if "val it = that" is inside the block, then hasNext on an empty
        // iterator will continually reevaluate it.  (ticket #3269)
        lazy val it = that.toIterator
        // the eq check is to avoid an infinite loop on "x ++ x"
        def hasNext = cur.hasNext || ((cur eq self) && {
          it.hasNext && {
            cur = it
            true
          }
        })
        def next() = { hasNext; cur.next() }
      }

在评论中,它说:// optimize a little bit to prevent n log n behavior.

连接两个迭代器何时以及如何导致 n log n ?

【问题讨论】:

  • 在“Scala 编程第二版”中提到。 log n 是由于必须在迭代的每个步骤中决定下一个元素来自第一个迭代器还是第二个迭代器而引入的额外间接性。
  • 如果检查哪个迭代器为空将一直执行,那么通过串联迭代器串联,您会得到一个糟糕的复杂性,这是通过将新值重新分配给 cur 来解决的
  • 非常感谢 :) 这很清楚。
  • 能否请您创建一个被接受的答案,这样问题就不会再出现在未回答的列表中了?
  • 你可以回答你自己的问题 Mik :)

标签: performance algorithm scala iterator


【解决方案1】:

根据大众的要求,我引用上面的@Paolo Falabella 评论回答我自己的问题:

在“Scala 编程第二版”中提到。日志 n 是由于 由于必须在每个步骤中做出决定而引入的额外间接性 如果下一个元素来自第一个或第二个元素,则迭代 迭代器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-21
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多