Objective-C reference counters

It’s interesting to look at the Objective-C runtime. I’ve been doing that a lot recently to bring D/Objective-C to life and found a couple of interesting things. For instance, do you know where the reference counts are stored?

They’re split between eight global hash tables in Core Foundation, each table protected by its own spin lock. The table is chosen according to a few bits in the object’s address… On iOS there’s only one global hash table. I guess all this is to avoid contention on multi-core machines. It’s still unexpected they don’t store the counter as a variable within the object itself.

I find it unexpected however that they’re not simply storing the reference counter directly as a variable inside the object. I guess there’s an advantage to gain by doing things like they do, but I don’t see it.

Reference: Runtime.c in Core Foundation’s internals


  • © 2003–2017 Michel Fortin.