What is the most efficient way to create empty ListBuffer?
Asked Answered
L

2

10

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?

Lylalyle answered 9/4, 2010 at 9:36 Comment(0)
E
14

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

Engelbert answered 9/4, 2010 at 9:51 Comment(0)
J
9

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.

Juliusjullundur answered 9/4, 2010 at 10:6 Comment(1)
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 youLylalyle

© 2022 - 2024 — McMap. All rights reserved.