From a8a88354703c93a628844cd8963d06c392290342 Mon Sep 17 00:00:00 2001 From: Hanton Yang Date: Thu, 28 Nov 2019 16:13:22 +0800 Subject: [PATCH] Use `queue` in `ASMainSerialQueue` For removing the first element, time complexity of `NSMutableArray` is O(n) while `queue` is O(1), which is more efficient. --- Source/Details/ASMainSerialQueue.mm | 35 +++++++++++++---------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/Source/Details/ASMainSerialQueue.mm b/Source/Details/ASMainSerialQueue.mm index 8b77c654b..472214390 100644 --- a/Source/Details/ASMainSerialQueue.mm +++ b/Source/Details/ASMainSerialQueue.mm @@ -11,38 +11,29 @@ #import #import +#import @interface ASMainSerialQueue () { AS::Mutex _serialQueueLock; - NSMutableArray *_blocks; + std::queue _blocks; } @end @implementation ASMainSerialQueue -- (instancetype)init -{ - if (!(self = [super init])) { - return nil; - } - - _blocks = [[NSMutableArray alloc] init]; - return self; -} - - (NSUInteger)numberOfScheduledBlocks { AS::MutexLocker l(_serialQueueLock); - return _blocks.count; + return _blocks.size(); } - (void)performBlockOnMainThread:(dispatch_block_t)block { { AS::MutexLocker l(_serialQueueLock); - [_blocks addObject:block]; + _blocks.push(block); } [self runBlocks]; @@ -53,13 +44,11 @@ - (void)runBlocks dispatch_block_t mainThread = ^{ AS::UniqueLock l(self->_serialQueueLock); do { - dispatch_block_t block; - if (self->_blocks.count > 0) { - block = _blocks[0]; - [self->_blocks removeObjectAtIndex:0]; - } else { + if (_blocks.empty()) { break; } + dispatch_block_t block = _blocks.front(); + _blocks.pop(); { l.unlock(); block(); @@ -73,7 +62,15 @@ - (void)runBlocks - (NSString *)description { - return [[super description] stringByAppendingFormat:@" Blocks: %@", _blocks]; + NSString *desc = [super description]; + std::queue blocks = _blocks; + [desc stringByAppendingString:@" Blocks: "]; + while (!blocks.empty()) { + dispatch_block_t block = blocks.front(); + [desc stringByAppendingFormat:@"%@", block]; + blocks.pop(); + } + return desc; } @end