Curious about Swift's memory internals? Mike Ash has your back.
Mike Ash's latest Friday Q&A takes a walk through weak references in Swift 4, comparing the old implementation against the new. From the article:
In the old implementation, Swift objects have two reference counts: a strong count and a weak count. When the strong count reaches zero while the weak count is still non-zero, the object is destroyed but its memory is not deallocated. This leaves a sort of zombie object sitting in memory, which the remaining weak references point to. When a weak reference is loaded, the runtime checks to see if the object is a zombie. If it is, it zeroes out the weak reference and decrements the weak reference count. Once the weak count reaches zero, the object's memory is deallocated. This means that zombie objects are eventually cleared out once all weak references to them are accessed.
In the old implementation, it's possible zombie objects could hang around long after they were needed, which could be a real waste of memory. Fortunately, times have moved on and Swift's new implementation manages to solve that problem using side tables. Mike explains:
Swift's new implementation of weak references brings with it the concept of side tables. A side table is a separate chunk of memory which stores extra information about an object. It's optional, meaning that an object may have a side table, or it may not. Objects which need the functionality of a side table can incur the extra cost, and objects which don't need it don't pay for it.
One thing I really enjoy about Mike's blog posts is that he is careful to link to the matching source code in Swift, so you can see for yourself exactly how things are implemented. Yes, I know all the Swift source code is there to read, but it can be so hard to find an entry point without someone to give you a pointer – make sure you read the whole article!
LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!
Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and a speaker at Swift events around the world. If you're curious you can learn more here.