Scala Buffer: Size or Length?

后端 未结 4 1718
無奈伤痛
無奈伤痛 2021-01-08 01:20

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

Both size and length methods are defined, inherited

相关标签:
4条回答
  • 2021-01-08 01:39

    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.

    0 讨论(0)
  • 2021-01-08 01:42

    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.

    0 讨论(0)
  • 2021-01-08 01:45

    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.

    0 讨论(0)
  • 2021-01-08 02:01

    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.

    0 讨论(0)
提交回复
热议问题