|
|
|
|
|
by olliej
1119 days ago
|
|
Swift's refcounting is atomic (as is objc's). As long as you're not under contention most benchmarks I've seen show negligible overhead (from the addition of atomicity, the refcount overhead is still there) for uncontended access. But IME if you do have many threads walking the same data structure you end up spending stupid amounts of time fighting the refcounting. This applies even if the data structure is immutable and has guaranteed lifetime as swift's type system doesn't seem to allow that to be expressed, and as a result it seems to do a lot of ref churn we'd consider unnecessary. |
|
Most of the time it’s possible to avoid atomic instructions and still be thread-safe. https://dl.acm.org/doi/10.1145/3243176.3243195:
“BRC is based on the observation that most objects are only accessed by a single thread, which allows most RC operations to be performed non-atomically. BRC leverages this by biasing each object towards a specific thread, and keeping two counters for each object --- one updated by the owner thread and another updated by the other threads. This allows the owner thread to perform RC operations non-atomically, while the other threads update the second counter atomically. We implement BRC in the Swift programming language runtime, and evaluate it with client and server programs. We find that BRC makes each RC operation more than twice faster in the common case. As a result, BRC reduces the average execution time of client programs by 22.5%, and boosts the average throughput of server programs by 7.3%.”
I remember reading that this made it into Swift, but cannot find it, so I’m not sure anymore.
And of course, the Swift compiler tries to avoid unnecessary refcount updates.