ArrayBuffer vs ArrayBuilder in scala

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)