3.6 · Retain traffic, parameter conventions, Unmanaged, bridging
ARC is not free, and a lot of its work is invisible in your source. Knowing where retains and releases hide, and how to opt out of them, separates “it works” from “it is fast”.
Mental model. Passing a reference borrows it. Storing or returning one takes ownership of it. Almost every hidden retain is one of those two moments.
The cost of counting
Where retains come from, and the calling conventions that decide them.
- Where do hidden retains and releases come from, and how do you reduce them?
Every time a class reference is copied, the compiler adds a retain, and a release when the copy goes away. The common sources: assigning or storing a reference… - What do guaranteed and owned parameters mean, and what do borrowing and consuming add?
The compiler decides ownership at each call boundary. By default a function borrows its parameters: the caller keeps ownership and guarantees the value lives…
Crossing into C and Objective-C
Manual ownership and the autoreleases that bridging adds.
- What is Unmanaged, and what do takeRetainedValue and takeUnretainedValue mean?
Unmanaged<T> wraps a class reference and opts out of ARC: you hold a plain pointer and manage the count yourself. passRetained(obj) gives you an unmanaged… - What hidden retains and autoreleases does calling Objective-C add?
Objective-C methods that return objects usually return them autoreleased (+0): the callee does not give you ownership, it just promises the object lives until…
More in Memory, ARC & runtime
- 3.1 · ARC, autorelease pools, object lifetime
- 3.2 · strong, weak, unowned, unowned(unsafe)
- 3.3 · Cycles: delegates, closures, timers, Combine, tasks
- 3.4 · Object layout, side tables, tagged pointers
- 3.5 · The copy-on-write mechanism
- 3.7 · Leaks, abandoned memory, footprint, and the tools
- 3.8 · deinit rules, process exit, isolated deinit, noncopyable types and consume
- 3.9 · Weak collections, nested closures, structs holding references, weak let and escaped pointers
- 3.10 · Enum layout, existential boxing, tail allocation, slice retention, growth and the command-line tools