ArrayBuffer和Array有什么区别 [英] What is the difference between ArrayBuffer and Array

查看:393
本文介绍了ArrayBuffer和Array有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是scala/java的新手,我很难弄清两者之间的区别.

I'm new to scala/java and I have troubles getting the difference between those two.

通过阅读scala doc 我理解ArrayBuffer是交互式的(追加,插入,前置等).

By reading the scala doc I understood that ArrayBuffer are made to be interactive (append, insert, prepend, etc).

1)实施的基本区别是什么?

1) What are the fundamental implementation differences?

2)两者之间是否存在性能差异?

2) Is there performance variation between those two?

推荐答案

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.

这篇关于ArrayBuffer和Array有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆