Skip to content

Instantly share code, notes, and snippets.

@Alexander-Ignition
Created September 13, 2022 13:18
Show Gist options
  • Save Alexander-Ignition/f5d35e221a25f435525ac54795ef029a to your computer and use it in GitHub Desktop.
Save Alexander-Ignition/f5d35e221a25f435525ac54795ef029a to your computer and use it in GitHub Desktop.
GCD Performance Anti-Pattern

Grand Central Dispatch Performance Anti-Pattern

WWDC18 What's New in LLVM at 16:48

Performance implications: slowdown and hangs

__block NSString *taskName = nil;
dispatch_semaphore_t sema = dispatch_semaphore_create(0); 

[self.connection.remoteObjectProxy requestCurrentTaskName:^(NSString *task) {
    taskName = task;
    dispatch_semaphore_signal(sema); 
}];

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); 
return taskName;
  • Blocks current thread by the execution on a different queue
  • The task queue usually has lower priority, leads to priority inversion
  • Spawns useless threads

If available, use synchronous version of the API

__block NSString *taskName = nil;
id remoteObjectProxy = [self.connection synchronousRemoteObjectProxyWithErrorHandler: ^(NSError *error) { 
    NSLog(@“Error: %@“, error); 
}]; 
[remoteObjectProxy requestCurrentTaskName:^(NSString *task) {
    taskName = task; 
}];
return taskName;

Alternatively, use the API in an asynchronous manner

[self.connection.remoteObjectProxy requestCurrentTaskName:^(NSString *task) { 
    completionHandler(task);
}];

Enabling check in build settings CLANG_ANALYZER_GCD_PERFORMANCE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment