looking at
val sb = seq.newbuilder[int] println(sb.getclass.getname) sb += 1 sb += 2 val s = sb.result() println(s.getclass.getname) the output is
scala.collection.mutable.listbuffer
scala.collection.immutable.$colon$colon
using scala 2.10.1.
i expect seq.newbuilder return vectorbuilder example. returned canbuildfrom, if result explicitly typed seq:
def build[t, c <: iterable[t]](x: t, y: t) (implicit cbf: canbuildfrom[nothing, t, c]): c = { val b = cbf() println(b.getclass.getname) b += x b += y b.result() } val s: seq[int] = build(1, 2) println(s.getclass.getname) // scala.collection.immutable.vector in case builder vectorbuilder, , result's class vector.
so explicitly wanted build seq, result list needs more ram, according scala collection memory footprint characteristics.
so why seq.newbuilder return listbuffer gives list in end?
the scala collections api complex , hierarchy rich in depth. each level represents sort of new abstraction. seq trait split 2 different subtraits, give different guarantees performance (ref.):
an
indexedseqprovides fast random-access of elements , fast length operation. 1 representative ofindexedseqvector.a
linearseqprovides fast access first element via head, has fast tail operation. 1 representative oflinearseqlist.
as current default implementation of seq list, seq.newbuilder return listbuffer. however, if want use vector can either use vector.newbuilder[t] or indexedseq.newbuilder[t]:
scala> scala.collection.immutable.indexedseq.newbuilder[int] res0: scala.collection.mutable.builder[int,scala.collection.immutable.indexedseq[int]] = scala.collection.immutable.vectorbuilder@1fb10a9f scala> scala.collection.immutable.vector.newbuilder[int] res1: scala.collection.mutable.builder[int,scala.collection.immutable.vector[int]] = scala.collection.immutable.vectorbuilder@3efe9969
Comments
Post a Comment