To iterate an Iterator, we can call its foreach or use while loop. The implementation of foreach is:
def foreach[U](f: A => U) { while (hasNext) f(next()) }
So I think foreach should as fast as while(iterator.hasNext), but after doing some test, the results surprise me very much.
my test code:
def getSize2[T](i: Iterator[T]) = {
var count = 0
val f = (a: T) => count += 1
while(i.hasNext) {
f(i.next)
}
count
}
def getSize3[T](i: Iterator[T]) = {
var count = 0
val f = (a: T) => count += 1
i.foreach(f)
count
}
It is very weird that getSize2 is 3 times faster than getSize3!
Anyone know what happened there?
Edit: paste my test program
def main(args: Array[String]) {
val data = 0 to 100000000
val start2 = System.nanoTime
(0 to 100).foreach(_ => getSize2(data.iterator))
println("get size, while loop, using function: " + (System.nanoTime - start2)/1000000)
val start3 = System.nanoTime
(0 to 100).foreach(_ => getSize3(data.iterator))
println("get size, foreach: " + (System.nanoTime - start3)/1000000)
}
My OS: ubuntu 12.04, scala version: 2.10.3