iOS Runloop和CADisplayLink 在輸入和輸出中的性能優(yōu)化

一、runloop線程保活

1.1 線程保活的作用:

使用子線程時(shí),如果任務(wù)非常頻繁,如檢測(cè)網(wǎng)絡(luò)狀態(tài),縮放,拖動(dòng)等觸發(fā)的事件,切換不同子線程會(huì)消耗大量cpu,如果是同一個(gè)常駐線程則可以避免該問題

1.2 在線程中啟動(dòng)一個(gè)runloop

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(runLoopThreadEntryPoint:) object:nil];
[thread start];

//實(shí)現(xiàn)線程入口方法:在線程入口方法中,創(chuàng)建并啟動(dòng)一個(gè) RunLoop。例如
- (void)runLoopThreadEntryPoint:(id)object {
    @autoreleasepool {
        // Create an autoreleased NSRunLoop object
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        self.runloop = runloop;
        // Add an input source to the run loop (for example, a timer or a custom input source)
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        
        // Run the run loop
        [runLoop run];
      
    }
}

1.3 插入任務(wù)

[NSObject performSelector: @selector(log) onThread: thread withObject: obj waitUntilDone: NO];
  [runLoop performBlock:^{
       if (block) block();
       if (completion) completion();
       dispatch_async(dispatch_get_main_queue(), ^{
           self.renderTaskCount--;
           if (isDrawBlock) [self flush];
       });
   }];

二、 CADisplayLink 同步屏幕刷新

前面大量任務(wù)產(chǎn)生結(jié)果,需要密集刷新顯示時(shí),可以使用CADisplayLink優(yōu)化, CADisplayLink 與NStimer類似,不過前者同步屏幕刷新時(shí)間,如60hz的調(diào)用周期時(shí)1/60s

CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkCallback:)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
- (void)displayLinkCallback:(CADisplayLink *)displayLink {
   // 在這里執(zhí)行需要執(zhí)行的任務(wù),例如更新界面或者計(jì)算動(dòng)畫狀態(tài)
}

三、其他

在多個(gè)任務(wù)持續(xù)輸入或輸出數(shù)據(jù)中,可以添加bool標(biāo)識(shí),即前一個(gè)任務(wù)未執(zhí)行完之前,下一個(gè)任務(wù)則跳過

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容