What is the difference between scala.collections.mutable.ArrayBuilder and scala.collections.mutable.ArrayBuffer? If, for instance, I need to build an Array[Int], which is preferrable to use? Is there any perfomance difference, like in java.lang.StringBuffer and java.lang.StringBuilder?
Scala provides a data structure, the ArrayBuffer, which can change size when initial size falls short. As array is of fix size and more elements cannot be occupied in an array, ArrayBuffer is an alternative to array where size is flexible. Internally ArrayBuffer maintains an array of current size to store elements.
Array in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size can't change.
ArrayBuilder
is a Builder
, and builders are meant to be used to construct other collections by adding elements to them. Builders are not usually meant to be used directly in client code.
ArrayBuffer
is a Buffer
and Seq
-- buffers are sequences to which you can efficiently append elements. Sequences come with a lot of auxiliary operations.
You probably need an ArrayBuffer
. It is meant to be used as an alternative to the ArrayList
in Java. The ArrayBuffer
class is a fully-powered sequence collections with all the bulk data operations like foreach
, map
, filter
, zip
and friends, unlike ArrayBuilder
which is equipped only with +=
to add elements and result
to obtain the array at the end.
One place where you might prefer an ArrayBuilder
is when you are instantiating it for a primitive type like Int
and you care about performance. In this case the ArrayBuilder
variants are specialized for different primitive types and hold an underlying array of a proper primitive type, whereas an ArrayBuffer
always holds an object array underneath -- every primitive you add to it undergoes boxing.
To instantiate an array buffer:
new ArrayBuffer[Int] // gives you an array buffer that will hold boxed integers
To instantiate an array builder:
new ArrayBuilder.ofInt // gives you a manually specialized array builder that will hold real primitives
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With