13

Scaladocs explain how to add an element to a Vector.

def :+(elem: A): Vector[A]
[use case] A copy of this vector with an element appended.

Example:

scala> Vector(1,2) :+ 3
res12: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)

For a large collection, it seems expensive to copy the whole Vector, and then add an element to it.

What's the best(fastest) way to add an element to a Vector?

3 Answers 3

9

Concatenation to an immutable Vector is O(logN). Take a look at this paper to see how it is done.

http://infoscience.epfl.ch/record/169879/files/RMTrees.pdf

Sign up to request clarification or add additional context in comments.

2 Comments

That can't be right. See this docs.scala-lang.org/overviews/collections/…. Append is "eC"
@Programmer did you read the paper? 6. Conclusions "The RRB-Tree based vector provides a viable extension to the existing 32-way immutable vector used in Clojure and Scala to provide O(logN) concatenation and splits while maintaining the basic costs associated with other operations. For practical purposes they can be considered constant time."
7

If you're going to be doing a lot of appends you should use a Queue as it guarantees constant time append. For information on the time complexity of collections you can refer to this cheat sheet.

http://www.scala-lang.org/docu/files/collections-api/collections_40.html

Comments

3

Appending to a vector in Scala takes effectively constant time. The vector is copied in the sense that many of its data structures are reused, not in the sense that all of the elements are copied into a new vector. See the link provided by coltfred for more information about time complexity of collections:

http://www.scala-lang.org/docu/files/collections-api/collections_40.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.