Swift Array vs ContiguousArray
We all use arrays day to day. But have we considered about using them efficiently? Here I am going to discuss about a technique by which we could improve our Array performance based on the Element inside it.
Array - Ideal Elements
Try to use value types in Array. When using value types, the optimizer can remove most of the overhead in Array that is necessary to handle the possibility of the array being backed an NSArray. By using value types without reference types, one can avoid additional retain, release traffic inside Array. But be careful and consider the tradeoff between using a large value type vs Reference type. You can read more about this here.
ContiguousArray
The ContiguousArray type is a specialized array that always stores its elements in a contiguous region of memory. If your array’s Element type is a class or @objc protocol and you do not need to bridge the array to NSArray or pass the array to Objective-C APIs, using ContiguousArray may be more efficient and have more predictable performance than Array. If the array’s Element type is a struct or enumeration, Array and ContiguousArray should have similar efficiency.
Consider the following class.
class Address {
var street = ""
var city = ""
var state = ""; enum AddressAttributes {
case Street
case City
case State
} func updateAttribute(value: String, attribute: AddressAttributes){
switch attribute {
case .Street:
street = value;
case .City:
city = value;
case .State:
state = value;
}
}
}
I have measured the average time needed to add objects of this class to an Array and ContiguousArray. I took an arbitrary value (1000000) just to demonstrate how this could behave differently on a larger scale.
func testPerformanceForClassArray() {
let address = Address()
var array: [Address] = []
self.measure {
for _ in 0..<10000000 {
array.append(address)
}
}
}func testPerformanceForClassContiguousArray() {
let address = Address()
var array: ContiguousArray<Address> = []
self.measure {
for _ in 0..<10000000 {
array.append(address)
}
}
}
Average time taken from 10 runs,
Array: 2.45s
ContiguousArray: 0.47s
The key takeaway here is that you could improve the performance significantly by using ContiguousArray array over a normal Array.
Thanks for reading :)
https://www.linkedin.com/in/nitin-george-012b3517