Friday, December 11, 2015

Swift’s Lazy Weak References

Mike Ash:

Weak references to an object will cause that object’s memory to remain allocated even after there are no strong references to it, until all weak references are either loaded or discarded. This temporarily increases memory usage. Note that the effect is small, because while the target object’s memory remains allocated, it’s only the memory for the instance itself.


Extra memory is required to store the weak reference count on every object. In practice it appears that this is inconsequential on 64-bit. The header fields want to occupy a whole number of pointer-sized chunks, and the strong and weak reference counts share one. If the weak reference count weren’t there, the strong reference count would just occupy all 64 bits by itself. It’s possible that the strong reference could otherwise be moved into the isa by using a non-pointer isa, but I’m not sure how important that is or how it’s going to shake out in the long term.

Joe Groff:

We do plan to make weak references use a side table implementation like ObjC so we can eagerly reclaim their memory.

It’s nice for perf, yeah, but leaking the memory is unacceptable for things like outlets and delegates that get hit infrequently.

Mike Ash:

The current implementation of weak references has a race condition when multiple threads read the same weak reference to a deallocating object simultaneously.

Previously: Weak and Unowned References in Swift, How Swift Implements Unowned and Weak References.

Update (2015-12-13): Here’s the mailing list discussion for the thread-safety bug.

Comments RSS · Twitter

Leave a Comment