Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to create empty ListBuffer?

What is the most efficient way to create empty ListBuffer ?

  1. val l1 = new mutable.ListBuffer[String]
  2. val l2 = mutable.ListBuffer[String] ()
  3. val l3 = mutable.ListBuffer.empty[String]

There are any pros and cons in difference?

like image 515
drypot Avatar asked Apr 09 '10 09:04

drypot


People also ask

What is ListBuffer?

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.

How do I create a mutable list in Scala?

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.


2 Answers

Order by efficient:

  1. new mutable.ListBuffer[String]
  2. mutable.ListBuffer.empty[String]
  3. mutable.ListBuffer[String] ()

You can see the source code of ListBuffer & GenericCompanion

like image 68
Eastsun Avatar answered Sep 26 '22 21:09

Eastsun


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.

like image 33
Michel Krämer Avatar answered Sep 24 '22 21:09

Michel Krämer