问题
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