In what cases I should use Array(Buffer) and List(Buffer). Only one difference that I know is that arrays are nonvariant and lists are covariant. But what about performance and some other characteristics?
In what cases I should use Array(Buffer) and List(Buffer). Only one difference that I
Share
Immutable Structures
The Scala
Listis an immutable recursive data structure which is such a fundamental structure in Scala, that you should (probably) be using it much more than anArray(which is actually mutable – the immutable analog ofArrayisIndexedSeq).If you are coming from a Java background, then the obvious parallel is when to use
LinkedListoverArrayList. The former is generally used for lists which are only ever traversed (and whose size is not known upfront) whereas the latter should be used for lists which either have a known size (or maximum size) or for which fast random access is important.Mutable Structures
ListBufferprovides a constant-time conversion to aListwhich is reason alone to useListBufferif such later conversion is required.A scala
Arrayshould be implemented on the JVM by a Java array, and hence anArray[Int]may be much more performant (as anint[]) than aList[Int](which will box its contents, unless you are using the very latest versions of Scala which have the new@specializedfeature).However, I think that the use of
Arrays in Scala should be kept to a minimum because it feels like you really need to know what is going on under the hood to decide whether your array really will be backed by the required primitive type, or may be boxed as a wrapper type.