Calling Seq(1,2,3)
and calling List(1,2,3)
will both result in a 1 :: 2 :: 3 :: Nil
. The Seq.apply
method is just a very generic method that looks like this:
def apply[A](elems: A*): CC[A] = {
if (elems.isEmpty) empty[A]
else {
val b = newBuilder[A]
b ++= elems
b.result()
}
}
newBuilder
is the thing that sort of matters here. That method delegates to scala.collection.immutable.Seq.newBuilder
:
def newBuilder[A]: Builder[A, Seq[A]] = new mutable.ListBuffer
So the Builder
for a Seq
is a mutable.ListBuffer
. A Seq
gets constructed by appending the elements to the empty ListBuffer
and then calling result
on it, which is implemented like this:
def result: List[A] = toList
/** Converts this buffer to a list. Takes constant time. The buffer is
* copied lazily, the first time it is mutated.
*/
override def toList: List[A] = {
exported = !isEmpty
start
}
List
also has a ListBuffer
as Builder
. It goes through a slightly different but similar building process. It is not going to make a big difference anyway, since I assume that most of your algorithm will consist of prepending things to a Seq
, not calling Seq.apply(...)
the whole time. Even if you did it shouldn't make much difference.
It's really not possible to say what is causing the behavior you're seeing without seeing the code that has that behavior.