'Scala mutable.ListBuffer prepend/append not constant

I have a listbuffer with some predefined set of elements and I am unable to figure out the behaviour difference of using :+, +: and +=

Using :+

object App {

  def main(args: Array[String]): Unit = {
    var b = scala.collection.mutable.ListBuffer.range(0,5000000)
    var i = 10
    while(i != 0) {
      println(measure {
        b = b.:+(1)
      })
      i = i - 1
    }
  }
}

63.273132 ms
1638.054828 ms
1341.641419 ms
53.644715 ms
474.193063 ms
63.242636 ms
330.665982 ms
79.725333 ms
290.109014 ms
55.515174 ms

Using +:

object App {

  def main(args: Array[String]): Unit = {
    var b = scala.collection.mutable.ListBuffer.range(0,5000000)
    var i = 10
    while(i != 0) {
      println(measure {
        b = b.+:(1)
      })
      i = i - 1
    }
  }
}

72.501386 ms
1675.274467 ms
1380.867864 ms
52.565501 ms
383.728268 ms
51.046573 ms
314.941445 ms
53.824498 ms
270.233627 ms
52.864131 ms

Using +=

object App {

  def main(args: Array[String]): Unit = {
    var b = scala.collection.mutable.ListBuffer.range(0,5000000)
    var i = 10
    while(i != 0) {
      println(measure {
        b = b+=1
      })
      i = i - 1
    }
  }
}

0.012685 ms
0.002234 ms
0.001569 ms
0.001383 ms
0.001398 ms
0.001499 ms
0.001413 ms
0.001416 ms
0.00147 ms
0.00136 ms

What's strange is :+ and +: use ++= eventually so why does it not act similarly? Benchmarking ++= yields similar result as +=.

Am I missing something in the usage of ListBuffer? What's the difference between the three methods?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source