Thank you. I hadn't noticed arr.swapAt() in the Array API.
For completeness, here is how the performance of various array swaps compares when run with swift -O
using arrRef and swapAt : [Int] - 0.8msec / [Obj] - 3.5msec
using arrRef and 1 pair : [Int] - 0.4msec / [Obj] - 3.2msec
using arrRef and 2 pairs: [Int] - 0.5msec / [Obj] - 5.6msec
using arrRef and verbose: [Int] - 0.4msec / [Obj] - 5.6msec
using self.arr and swapAt : [Int] - 1.6msec / [Obj] - 3.8msec
using self.arr and 1 pair : [Int] - 159.0msec / [Obj] - 15600.0msec
using self.arr and 2 pairs: [Int] - 1.5msec / [Obj] - 8.2msec
using self.arr and verbose: [Int] - 1.4msec / [Obj] - 6.9msec
Sample code with arrRef:
func swapsTestUsingReference(_ arrRef: inout [T], _ repeats: Int) {
let size = arrRef.count
for i in 0..<repeats {
let index1 = i % size
let index2 = (i + 1) % size
// using swapAt
//arrRef.swapAt(index1, index2)
// using 1 pair
//(arrRef[index1], arrRef[index2]) = (arrRef[index2], arrRef[index1])
// using 2 pairs
// let (v1, v2) = (arrRef[index1], arrRef[index2]);
// (arrRef[index2], arrRef[index1]) = (v1, v2);
// using verbose
//let v1 = arrRef[index1]
//let v2 = arrRef[index2]
//arrRef[index2] = v1
//arrRef[index1] = v2
}
}
Topic:
Programming Languages
SubTopic:
Swift
Tags: