inessential by Brent Simmons

dispatch_once

I’ve been doing this for years when I have a static thing and I want to set its value once:

static MyThing *foo = nil;
static dispatch\_once\_t onceToken;
dispatch\_once(&onceToken, ^{
  foo = [some thing];
});

But lately I’ve been doing this:

static MyThing *foo = nil;
if (!foo) {
  foo = [some thing];
}

The advantage of dispatch\_once is that it’s thread-safe — it’s one less thing to worry about when worrying about concurrency.

But here’s the thing: almost all of the code I write runs on the main thread only. And, furthermore, when I use this pattern it’s almost always in UI code (which is main thread code). (For example: initializing a gradient that won’t change and should be kept in memory.)

So dispatch\_once isn’t valuable in those cases. And, worse, it could hide bugs. (If my main thread code isn’t running on the main thread, I need to see some problems as a result.)

I’ll keep using dispatch\_once in the ever-more-rare cases where concurrency is actually an issue — but, where it’s not, I’m back to the old-fashioned way.

And the old-fashioned way is less code and easier to read, which I don’t mind at all.