I'm new to scala/java and I have troubles getting the difference between those two.
By reading the scala doc I understood that ArrayBuffer
are made to be interactive (append, insert, prepend, etc).
1) What are the fundamental implementation differences?
2) Is there performance variation between those two?
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".
Generally speaking: Buffers store an array of unformatted memory. An array is a general term of contiguous memory. A buffer needs to be bound to the context, whereas an array is just an array of data.
Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”. Uint16Array – treats every 2 bytes as an integer, with possible values from 0 to 65535.
What is an ArrayBuffer? As per the Scala Documentation, an ArrayBuffer is a mutable data structure which allows you to access and modify elements at specific index. Compared to the previous tutorial on Array, an ArrayBuffer is resizable while an Array is fixed in size.
Both Array
and ArrayBuffer
are mutable, which means that you can modify elements at particular indexes: a(i) = e
ArrayBuffer
is resizable, Array
isn't. If you append an element to an ArrayBuffer
, it gets larger. If you try to append an element to an Array
, you get a new array. Therefore to use Array
s efficiently, you must know its size beforehand.
Array
s are implemented on JVM level and are the only non-erased generic type. This means that they are the most efficient way to store sequences of objects – no extra memory overhead, and some operations are implemented as single JVM opcodes.
ArrayBuffer
is implemented by having an Array
internally, and allocating a new one if needed. Appending is usually fast, unless it hits a limit and resizes the array – but it does it in such a way, that the overall effect is negligible, so don't worry. Prepending is implemented as moving all elements to the right and setting the new one as the 0th element and it's therefore slow. Appending n elements in a loop is efficient (O(n)), prepending them is not (O(n²)).
Array
s are specialized for built-in value types (except Unit
), so Array[Int]
is going to be much more optimal than ArrayBuffer[Int]
– the values won't have to be boxed, therefore using less memory and less indirection. Note that the specialization, as always, works only if the type is monomorphic – Array[T]
will be always boxed.
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