The length and size methods on ListBuffer differ. The former is overridden in ListBuffer.scala to have an O(1) implementation, but the latter forwards to "underlying", which uses the O(n ) implementation from TraversableOnce.
To reproduce,
def time[A](f: => A): A = {
val t1 = System.currentTimeMillis
val ret = f
val t2 = System.currentTimeMillis
println("%g secs".format((t2 - t1)/1000.))
ret
}
val lb = collection.mutable.ListBuffer.tabulate[Int](1000*1000)(identity)
time(for (j <- 0 until 10000) { lb.length })
time(for (j <- 0 until 10000) { lb.size })
The length and size methods on ListBuffer differ. The former is overridden in ListBuffer.scala to have an O(1) implementation, but the latter forwards to "underlying", which uses the O(n ) implementation from TraversableOnce.
To reproduce,
I get,
The issue came up on StackOverflow, where Daniel Sobral explained the behavior, http://stackoverflow.com/questions/7061842/what-is-the-running-time-for-size-on-scalas-listbuffer
It would also be nice to update the ScalaDoc for
ListBuffer.length
andsize
with performance characteristics.