views:

131

answers:

3

What would be the best Scala collection (in 2.8+), mutable or immutable, for the following scenario:

  • Sequentially ordered, so I can access items by position (a Seq)
  • Need to insert items frequently, so the collection must be able to grow without too much penalty
  • Random access, frequently need to remove and insert items at arbitrary indexes in the collection

Currently I seem to be getting good performance with the mutable ArrayBuffer, but is there anything better? Is there an immutable alternative that would do as well? Thanks in advance.

+3  A: 

Mutable: ArrayBuffer
Immutable: Vector

user100746
+2  A: 

Vector. IndSeq from scalaz should be even better.

Alexey Romanov
And Rope in the upcoming 5.1 release of Scalaz.
Apocalisp
It should be (very) slightly worse at "frequently need to remove and insert items at arbitrary indexes".
Alexey Romanov
+3  A: 

If you insert items at random positions more than log(N)/N of the time that you access them, then you should probably use immutable.TreeSet as all operations are O(log(N)). If you mostly do accesses or add to the (far) end, ArrayBuffer and Vector work well.

Rex Kerr
Thanks for your informative answer!
Johan Nystrom