If dispatch_sync does not use a different thread, can it be faster?

纵然是瞬间 提交于 2019-12-08 13:02:59

问题


I'm running this code

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
      NSLog(@"Main Thread? %d", [NSThread isMainThread]);
      // non-trivial non-UI code here

});

The NSLog indicates that I'm actually on the main thread, but... my impression is that the non-trivial non-UI code runs much faster if I use dispatch_sync (as opposed to nothing).

If it is running on the main thread, is there any way it could be faster?


回答1:


The global concurrent GCD queues have no ordering, passing one of them to dispatch_sync() is a noop and dispatch_sync() will just execute the specified block directly in this case, as if you had written

^{...}();



回答2:


By limiting the number of threads running, technically sure you may improve performance, however this isn't recommended. If you have a task that will take a substantial amount of time (substantial meaning, will the user experience be affected by an unresponsive UI) then just use a new thread using dispatch_async or an inline block (closure). The best option is to optimize your algorithm to improve the length of your task.

You won't notice a significant enough difference in speed by running on the main thread.



来源:https://stackoverflow.com/questions/14742184/if-dispatch-sync-does-not-use-a-different-thread-can-it-be-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!