2

I understand the basic concepts behind both, but I am wondering which is best to use for what type of structure for optimal complexity.

Is the general consensus that you simply use Array when you know the length of the structure you're creating and then ArrayBuffer when the length is unknown?

However, what confuses me is that it is stated Array is more efficient for built-in Scala types such as Int, String and so on. Does this also apply to the use case where you simply initiate an Array[Int] and then add values to it with :+= or is it only when it has the fixed length?

I assume that in cases where you know the length is unknown and you are working with datatypes other than the built-in ones the best solution would be ArrayBuffer, but I'm unsure of when built-in ones are used.

And what if you have a matrix, lets say Array[Array[Int]]. Is this the most optimal if you will be adding rows to it with :+=? Or maybe in that case it should be ArrayBuffer[Array[Int]]?

osk
  • 790
  • 2
  • 10
  • 31
  • You're making some claims that Array's performance for built in types are better than user defined ones I was not aware of. In Scala, it's common to prefer immutable data structures (e.g. Arrays) over mutable data structures such as ArrayBuffers, and it's very common in Scala to see people adding Arrays together and avoiding ArrayBuffers entirely for the purpose of following a pattern they believe leads to more robust code. – Philluminati Jan 09 '18 at 10:43
  • @Philluminati those claims I got from the first answer, last paragraph on this question https://stackoverflow.com/questions/31213733/what-is-the-difference-between-arraybuffer-and-array-in-scala/31213983 – osk Jan 09 '18 at 10:44
  • 1
    @Philluminati Arrays are mutable in Scala. `val a = Array(1); a(0) = 2;` – isomarcte Jan 09 '18 at 11:29

2 Answers2

2

The different between Array and ArrayBuffer boils down to the amortized cost of resizing the array storage.

For exact details you can read this post:

If you can determine ahead of time the storage requirements of your data, then Array will be better than ArrayBuffer since you don't need that book-keeping that is done by ArrayBuffer.

tuxdna
  • 8,257
  • 4
  • 43
  • 61
1

Generally Array is preferred when you need a fixed size collection and ArrayBuffer is much better when you need to add or remove elements from the end.

However, what confuses me is that it is stated Array is more efficient for built-in Scala types such as Int, String and so on

Array is much better when dealing with AnyVal types, so Int, Long, Float, Double, Boolean, Byte, Short, Char. This doesn't apply to String or any other AnyRef type. This is because normally when primitives are used as generic types they need to be boxed into object wrappers but with Array they don't.

This is more obvious in Java where Boxed and unboxed primitives have different types but boxing happens in Scala too, and it can make a big difference.

puhlen
  • 8,400
  • 1
  • 16
  • 31