Difference between Array and List in scala

前端 未结 3 763
[愿得一人]
[愿得一人] 2020-12-12 08:21

In what cases I should use Array(Buffer) and List(Buffer). Only one difference that I know is that arrays are nonvariant and lists are covariant. But what about performance

3条回答
  •  渐次进展
    2020-12-12 09:14

    In addition to the answers posted already, here are some specifics.

    While an Array[A] is literally a Java array, a List[A] is an immutable data structure that is either Nil (the empty list) or consists of a pair (A, List[A]).

    Performance differences

                              Array  List
    Access the ith element    θ(1)   θ(i)
    Delete the ith element    θ(n)   θ(i)
    Insert an element at i    θ(n)   θ(i)
    Reverse                   θ(n)   θ(n)
    Concatenate (length m,n)  θ(n+m) θ(n)
    Count the elements        θ(1)   θ(n)
    

    Memory differences

                              Array  List
    Get the first i elements  θ(i)   θ(i)
    Drop the first i elements θ(n-i) θ(1)
    Insert an element at i    θ(n)   θ(i)
    Reverse                   θ(n)   θ(n)
    Concatenate (length m,n)  θ(n+m) θ(n)
    

    So unless you need rapid random access, need to count elements, or for some reason you need destructive updates, a List is better than an Array.

提交回复
热议问题