tags:

views:

102

answers:

2

What is the most efficient way to create emtpy 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 ?

+4  A: 

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

Eastsun
+5  A: 

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.

Michel Krämer
I searched for some source code.'object Map' has def empty[A, B]: Map[A, B] = new HashMap[A, B]buf 'object ListBuffer' doesn't def empty. :(ListBuffer.empty looks have overhead as you say.Thank you
drypot