且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ArrayBuffer和Array有什么区别

更新时间:2023-11-06 11:31:52

ArrayArrayBuffer都是可变的,这意味着您可以在特定索引处修改元素:a(i) = e

Both Array and ArrayBuffer are mutable, which means that you can modify elements at particular indexes: a(i) = e

ArrayBuffer可调整大小,Array不可调整.如果将元素附加到ArrayBuffer,它将变大.如果尝试将元素追加到Array,则会得到一个新数组.因此,要有效使用Array,必须事先知道其大小.

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 Arrays efficiently, you must know its size beforehand.

Array在JVM级别上实现,并且是唯一未擦除的通用类型.这意味着它们是存储对象序列的最有效方法–无需额外的内存开销,并且某些操作被实现为单个JVM操作码.

Arrays 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是通过内部具有Array并在需要时分配一个新的实现的.追加通常是快速的,除非达到极限并调整数组的大小–但是这样做的方式是整体效果可以忽略不计,因此不必担心.前置是通过将所有元素向右移动并将新元素设置为第0个元素来实现的,因此它很慢.在循环中添加 n 个元素非常有效( O ( n )),而在元素前添加一个元素( O ( n ²)).

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专门用于内置值类型(Unit除外),因此,Array[Int]ArrayBuffer[Int]最优得多–不必将值装箱,因此使用更少的内存和更少的间接访问.请注意,像往常一样,仅当类型为单态时,专业化才有效– Array[T]将始终装箱.

Arrays 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.