您的位置:首页 > 其它

Scala中Array和List的区别

2015-12-09 14:03 423 查看
Difference between Array and List in scala

Q:什么时候用Array(Buffer)和List(Buffer)?

A: Scala中的List是不可变的递归数据(immutable recursive data),是Scala中的一种基础结构,你应该多用List而不是Array(Array实际上是mutable,不可变(immutable)的Array是IndexedSeq

Mutable Structures

ListBuffer提供一个常数时间的转换到List。

一个Scala的Array应该是由Java array生成的,因此一个Array[Int]也许比List[Int]更有效率。

但是,我认为Scala中数组尽量少用,因为它感觉是你真的需要知道底层发生了什么,来决定是否Array将所需的基本数据类型进行备份,或者可能boxed as a wrapper type.

Performance differencesArrayList
Access the ith elementO(1)O(i)
Discard the ith elementO(n)O(i)
Insert an element at iO(n)O(i)
ReverseO(n)O(n)
Concatenate (length m,n)O(n+m)O(n)
Calculate the lengthO(1)O(n)
memory differencesArrayList
Get the first i elementsO(i)O(i)
Drop the first i elementsO(n-i)O(1)
Insert an element at iO(n)O(i)
ReverseO(n)O(n)
Concatenate (length m,n)O(n+m)O(n)
所以,除非你需要快速随机访问或需要count batches of elements,否则,列表比数组更好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: