@synchronized vs dispatch_once

来源:互联网 发布:手机qq视频录像软件 编辑:程序博客网 时间:2024/05/21 04:42

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

原创粉丝点击