Scala Buffer: Size or Length?

2020-03-10 23:48发布

I am using a mutable Buffer and need to find out how many elements it has.

Both size and length methods are defined, inherited from separate traits.

Is there any actual performance difference, or can they be considered exact synonyms?

4条回答
仙女界的扛把子
2楼-- · 2020-03-11 00:07

In this case, they can be considered synonyms. You may want to watch out with some other cases such as Array - whilst length and size will always return the same result, in versions prior to Scala 2.10 there may be a boxing overhead for calling size (which is provided by a Scala wrapper around the Array), whereas length is provided by the underlying Java Array.

In Scala 2.10, this overhead has been removed by use of a value class providing the size method, so you should feel free to use whichever method you like.

查看更多
放我归山
3楼-- · 2020-03-11 00:07

They are synonyms, as the scaladoc for Buffer.size states:

The size of this buffer, equivalent to length.

The scaladoc for Buffer.length is explicit too:

The length of the buffer. Note: xs.length and xs.size yield the same result.

Simple advice: refer to the scaladoc before asking a question.

UPDATE: Just saw your edit adding mention of performance. As Daniel C. Sobral aid, one is normally always implemented in term of the other, so they have the same performance.

查看更多
forever°为你锁心
4楼-- · 2020-03-11 00:13

As of Scala-2.11, these methods may have different performance. For example, consider this code:

val bigArray = Array.fill(1000000)(0)
val beginTime = System.nanoTime()
var i = 0
while (i < 2000000000) {
  i += 1
  bigArray.length
}
val endTime = System.nanoTime()
println(endTime - beginTime)
sys.exit(-1)

Running this on my amd64 computer gives about 2423834 nanos time (varies from time to time).

Now, if I change the length method to size, it will become about 70764719 nanos time.

This is more than 20x slower.

Why does it happen? I didn't dig it through, I don't know. But there are scenarios where length and size perform drastically different.

查看更多
家丑人穷心不美
5楼-- · 2020-03-11 00:21

They are synonyms, mostly a result of Java's decision of having size for collections and length for Array and String. One will always be defined in terms of the other, and you can easily see which is which by looking at the source code, the link for which is provided on scaladoc. Just find the defining trait, open the source code, and search for def size or def length.

查看更多
登录 后发表回答