I have a very large list of numbers and I would like to pass it to a function to do some manipulations to it. Originally, I created a function with an inout property. As many know, inout in swift does NOT pass by reference, rather it makes an initial copy to the function then copies the values back on the return. This sounds expensive. I decided to wrap my list in a class and pass by reference in order to optimize and reduce time for copying. Interestingly enough, it seems that the inout function is faster than the pass by reference function. I even make a manipulation to the inout variable to cause the compiler to copy-on-write. Any ideas why the inout function is faster than the pass by reference?
class ReferencedContainer {
var container = [Int:Bool]()
}
func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for \(title): \(timeElapsed) s.")
}
func inoutTest(list: inout [Int]?) -> [Int]? {
list![0]=1
return list
}
func refTest(list: ReferencedContainer) -> ReferencedContainer {
list.container[0] = true
return list
}
var list : [Int]? = [Int]()
for i in 0...10000 {
list?.append(i)
}
var ref = ReferencedContainer()
for i in list!
{
ref.container[i] = true
}
printTimeElapsedWhenRunningCode(title: "refTest", operation: { refTest(list: ref)})
printTimeElapsedWhenRunningCode(title: "inout", operation: { inoutTest(list: &list)})
Time elapsed for refTest: 0.0015590190887451172 s.
Time elapsed for inout: 0.00035893917083740234 s.