【发布时间】: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