What’s the difference between Array<T>, ContiguousArray<T>, and ArraySlice<T> in Swift?
From the docs:
ContiguousArray:
Efficiency is equivalent to that of Array, unless T is a class or @objc protocol type, in which case using ContiguousArray may be more efficient. Note, however, that ContiguousArray does not bridge to Objective-C. See Array, with which ContiguousArray shares most properties, for more detail.
Basically, whenever you would store classes or @objc protocol types in an array, you might want to consider using ContiguousArray
instead of an Array
.
ArraySlice
ArraySlice always uses contiguous storage and does not bridge to Objective-C.
Warning: Long-term storage of ArraySlice instances is discouraged
Because a ArraySlice presents a view onto the storage of some larger array even after the original array's lifetime ends, storing the slice may prolong the lifetime of elements that are no longer accessible, which can manifest as apparent memory and object leakage. To prevent this effect, use ArraySlice only for transient computation.
ArraySlices are used most of the times when you want to get a subrange from an Array, like:
let numbers = [1, 2, 3, 4]
let slice = numbers[Range<Int>(start: 0, end: 2)] //[1, 2]
Any other cases you should use Array
.
Good source on different class of Swift is : http://swiftdoc.org/
Array is very clear so lets talk about other two.
ContiguousArray: http://swiftdoc.org/type/ContiguousArray/
A fast, contiguously-stored array of T.
Efficiency is equivalent to that of Array, unless T is a class or @objc protocol type, in which case using ContiguousArray may be more efficient. Note, however, that ContiguousArray does not bridge to Objective-C. See Array, with which ContiguousArray shares most properties, for more detail.
ArraySlice : http://swiftdoc.org/type/ArraySlice/
The Array-like type that represents a sub-sequence of any Array, ContiguousArray, or other ArraySlice.
ArraySlice always uses contiguous storage and does not bridge to Objective-C.
In short:
ContiguousArray is for more efficiency when T is a class or @objc protocol type ArraySlice is to represent Array in sub part.
There is new doc from Apple. https://git.io/vg5uw
So,
ContiguousArray<Element>
is the fastest and simplest of the three—use this when you need "C array" performance. The elements of a ContiguousArray are always stored contiguously in memory.
.
Array<Element>
is likeContiguousArray<Element>
, but optimized for efficient conversions from Cocoa and back—when Element can be a class type,Array<Element>
can be backed by the (potentially non-contiguous) storage of an arbitrary NSArray rather than by a Swift ContiguousArray.Array<Element>
also supports up- and downcasts between arrays of related class types. When Element is known to be a non-class type, the performance ofArray<Element>
is identical to that ofContiguousArray<Element>
.