voromax
voromax

Reputation: 3389

How to optimise dispatch queue creation

I am trying to implement a function which creates my custom high priority serial queue to be accessed in various objects similarly to dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)

To be sure that this queue is created only once I'm using dispatch once pattern. But I'm experiencing the performance problem. My function is three times slower. Here is the code:

dispatch_queue_t dispatch_get_custom_serial_queue() {
    static dispatch_once_t onceToken;
    static dispatch_queue_t CustomSerialQueue = nil;
    dispatch_once(&onceToken, ^{
        CustomSerialQueue = dispatch_queue_create("custom.serial.queue", DISPATCH_QUEUE_SERIAL);
        dispatch_set_target_queue(CustomSerialQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
    });
    return CustomSerialQueue;
}

Here is the test:

- (void)testQueueCreation
{
    CFAbsoluteTime startTime;

    NSLog(@"****************************");

    startTime = CFAbsoluteTimeGetCurrent();
    dispatch_queue_t queue = dispatch_get_custom_serial_queue();
    for (int i = 0; i < 1000000; i ++) {
        dispatch_sync(queue, ^{
            //
        });
    }
    NSLog(@"assign queue once:\t %f seconds", CFAbsoluteTimeGetCurrent() - startTime);

    startTime = CFAbsoluteTimeGetCurrent();
    for (int i = 0; i < 1000000; i ++) {
        dispatch_sync(dispatch_get_custom_serial_queue(), ^{
            //
        });
    }
    NSLog(@"get queue each time:\t %f seconds", CFAbsoluteTimeGetCurrent() - startTime);

    startTime = CFAbsoluteTimeGetCurrent();
    for (int i = 0; i < 1000000; i ++) {
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            //
        });
    }
    NSLog(@"get global queue each time:\t %f seconds", CFAbsoluteTimeGetCurrent() - startTime);

    NSLog(@"****************************");
}

And this is the result:

****************************
assign queue once: 0.035383 seconds
get queue each time: 0.112233 seconds
get global queue each time: 0.044906 seconds
****************************

What do I miss and how to make this function faster?

Upvotes: 1

Views: 84

Answers (2)

rob mayoff
rob mayoff

Reputation: 385580

If you want to make dispatch_get_custom_serial_queue faster, get rid of the dispatch_once. Create the queue in main before calling UIApplicationMain or NSApplicationMain to guarantee it'll exist later when needed.

Upvotes: 1

Kazuki Sakamoto
Kazuki Sakamoto

Reputation: 13999

dispatch_get_global_queue doesn't use dispatch_once. The function just gets a static variable.

I think dispatch_queue_t queue = dispatch_get_custom_serial_queue(); and dispatch_sync(queue, is a good idea for this case.

Upvotes: 1

Related Questions