What is the most efficient way to create empty ListBuffer ?
val l1 = new mutable.ListBuffer[String]val l2 = mutable.ListBuffer[String] ()val l3 = mutable.ListBuffer.empty[String]There are any pros and cons in difference?
Companion object ListBufferA Buffer implementation backed by a list. It provides constant time prepend and append. Most other operations are linear. A. the type of this list buffer's elements.
Because a List is immutable, if you need to create a list that is constantly changing, the preferred approach is to use a ListBuffer while the list is being modified, then convert it to a List when a List is needed. The ListBuffer Scaladoc states that a ListBuffer is “a Buffer implementation backed by a list.
Order by efficient:
new mutable.ListBuffer[String] mutable.ListBuffer.empty[String]mutable.ListBuffer[String] ()You can see the source code of ListBuffer & GenericCompanion
new mutable.ListBuffer[String] creates only one object (the list buffer itself) so it should be the most efficient way. mutable.ListBuffer[String] () and mutable.ListBuffer.empty[String] both create an instanceof scala.collection.mutable.AddingBuilder first, which is then asked for a new instance of ListBuffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With