现在的位置: 首页 > 综合 > 正文

@synchronized vs dispatch_once

2014年01月01日 ⁄ 综合 ⁄ 共 1009字 ⁄ 字号 评论关闭

From: http://bjhomer.blogspot.jp/2011/09/synchronized-vs-dispatchonce.html

@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.

【上篇】
【下篇】

抱歉!评论已关闭.