Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayBuffer vs ArrayBuilder in scala

Tags:

scala

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?

like image 819
Alexander Tokarev Avatar asked Apr 05 '13 17:04

Alexander Tokarev


People also ask

What is ArrayBuffer in Scala?

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.

Is array mutable in Scala?

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.


1 Answers

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 
like image 67
axel22 Avatar answered Sep 20 '22 12:09

axel22