I've got a function which takes a closure as an argument, and invokes it many times in a tight loop, once for every member in a large collection. The closure being passed captures exactly one class instance, and I have noticed that when I profile this code, Swift retain and Swift release are eating up a significant amount of CPU time. I've noticed that by wrapping the object in
Unmanaged and getting an unretained instance in the closure body removes this retain/release cost.
So my assumption would have been that the closure would retain the objects it captures when it's created, and it would release those objects when the closure itself is deallocated, but it looks as if that's not the case. I.e: if retain/release were only being executed once in the closure's lifetime, it does not make sense that the CPU time spent on those operations should eclipse the cost of the rest of the operations within the closure.
So my questions are:
Is that correct? Are captured class instances retained/released once per closure invocation? (b.t.w. this is a non-escaping closure if it matters)
If so, why is that the case? It seems like this comes at a significant performance cost, and there would never be a case where it would offer an advantage over retaining for the lifetime of the closure.