Thursday, September 29, 2011

@synchronized vs dispatch_once

In the comments on a recent Stack Overflow question, someone asked me if there was a significant performance difference between @synchronized and dispatch_once in implementing a singleton. So I wrote a simple test harness to access a singleton using the @synchronized method shown here:

@synchronized(self) {
    if (!synchronizedVar) {
        synchronizedVar = [[Test alloc] init];
    }
}
return synchronizedVar;

and the dispatch_once method shown here:


static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
	dispatchVar = [[Test alloc] init];
});
return dispatchVar;

Each test accessed the singleton object 10 million times. I ran both single-threaded tests and multi-threaded tests. Here were the results:



Single threaded results
-----------------------
  @synchronized: 3.3829 seconds
  dispatch_once: 0.9891 seconds

Multi threaded results
----------------------
  @synchronized: 33.5171 seconds
  dispatch_once: 1.6648 seconds
So yeah, dispatch_once is a lot faster, especially under thread contention. You can find my test harness on github.