Scala Buffer: Size or Length?

后端 未结 4 1763
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题