does iterator.next really have to call hasNext

242 views
Skip to first unread message

Koert Kuipers

unread,
Mar 4, 2015, 8:38:29 PM3/4/15
to scala-user
i am looking at the code in scala/src/library/scala/collection/Iterator.scala, and when reading methods that create new iterators or do transformations on iterators, i noticed that they always call hasNext in the next method. for example:

  def tabulate[A](end: Int)(f: Int => A): Iterator[A] = new AbstractIterator[A] {
    private var i = 0
    def hasNext: Boolean = i < end
    def next(): A =
      if (hasNext) { val result = f(i); i += 1; result }
      else empty.next()
  }


i always assumed usage of iterators involves calling hasNext before calling next. since next also always/often calls hasNext, this basically means hasNext gets called twice for every next invocation. is this really necessary?

is the jvm smart enough to optimize these redundant calls to hasNext?

could the iterator contract be such that hasNext should always be called before next, making the call to hasNext inside next unnecessary?

or maybe should i not even worry about this at all?

best, koert

Rex Kerr

unread,
Mar 4, 2015, 8:44:55 PM3/4/15
to Koert Kuipers, scala-user
The JVM can often (but not always--depends on the iterator and other context) elide the extra check, and if it's an easy check it's very inexpensive anyway (in cache and everything the second time through).

The normal routine is to use hasNext so that the appropriate error can be generated.  For instance, in tabulate the contract is that you will only have end items, but if you don't check hasNext then you can generate arbitrarily many.  Sometimes this will be okay, but not in general, and so the code must check (and hope that the JVM and CPU manage to make the redundancy non-problematic).

  --Rex

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages