ContiguousArray

The Swift standard library provides different data types that represent multiple elements in a collection - one of these types is ContiguousArray.

Compared to Array, which is usually the most commonly used data type, ContiguousArray is fairly unknown. In order to understand the difference between both types and when to use them, it’s necessary to know how Swift stores the containing elements in memory. Swift categories these elements into two different types:

  • Value Types
  • Reference Types

I’m not going to explain the fundamental difference between these types in this article but if you want to learn more about them check out Apple’s post. For now, it’s enough to know that each value type instance keeps a unique copy of its data, where instances of reference types share a single copy of data. So in other words, each time you copy a value type the containing data gets stored inside a new memory block, whereas when you copy a reference type the new copy points to the memory block of the original copy.

In an Array value types will be automatically stored in contiguous memory blocks. References types may be stored in non-contiguous memory blocks - since they are already existing in memory.

ContiguousArray, however, will always use contiguous memory blocks no matter what the stored data type is. This improves performance when looping through the elements for example.

// Array
let rangeOne = Array<Int>(1...10)

// ContiguousArray 
let rangeTwo = ContiguousArray<Int>(1...10)

Just like Array, ContiguousArray is implemented as a generic collection and conforms to the Collection Protocol, which means that the elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.

 

So if you need a little performance boost, give ContiguousArray a try.

Written on May 18, 2019