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

查看:37
本文介绍了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 并根据需要分配一个新数组来实现的.追加通常很快,除非它达到限制并调整数组大小——但它以这样一种方式进行,整体影响可以忽略不计,所以不用担心.Prepending 实现为将所有元素向右移动并将新元素设置为第 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 专门用于内置值类型(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天全站免登陆