Why Reference Counters All Start with +1?

This question can seem a bit theoretical, but while looking through ARC subject I discovered that as per swift/stdlib/public/SwiftShims/RefCount.h

- The strong RC is stored as an extra count: when the physical field is 0 the logical value is 1.
- The unowned RC also has an extra +1 on behalf of the strong references
- The weak RC also has an extra +1 on behalf of the unowned references

I'm wondering why an object initialises with +1 to all counters, what's the point of making extras?

Thanks for the feedback!

1 Like

It doesn't initialize with +1 to the counter, but effectively -1 to the counter; quoting line 51: "when the physical field is 0 the logical value is 1". The physical field is the value written to memory.

My impression is that the purpose is that freshly initialized (and zeroed) memory already has the correct value in it. This code gets executed very large numbers of times and, in such amounts, every optimization counts.

4 Likes

The physical field is the value written to memory.

Thank you for the clarification on physical field.
So you mean, that is a performance measure? I got the same suggestion at stackoverflow.

Also, elaborating on last two points from the RefCount.h quote (unowned / weak has extra +1 on behalf of strong / unowned) and connecting it to your assumption - when the object is initialised - it has refcounts: s/w/u: 0/0/0 (as logical values(?)). Well, that makes sense. Unfortunately yet I didn't succeed at finding more information in web, but I'll post it here when I do.

Thank you!