萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

iOS 應用效能優化核心技巧:ARC、reuseIdentifier、Opaque View、XIB 拆分、主執行緒保護

前言

本文精選自 25 條 iOS 效能優化建議中的前 5 條核心技巧,針對記憶體管理、列表重用、GPU 混合優化、介面載入速度、執行緒模型進行深度解析,並提供可直接落地的代碼模式與檢測方法。

1. 使用 ARC (Automatic Reference Counting) 進行記憶體管理

ARC 核心優勢

  • 編譯期自動插入 retain/release/autorelease,消除人為疏漏
  • 對象零強引用時即時釋放,降低記憶體峰值
  • 消除 dealloc 手寫錯誤風險

對比:手動 vs ARC


// 手動管理 (易忘 release 導致洩漏)
UIView *view = [[UIView alloc] init];
// ... 使用 view
[self.view addSubview:view];
[view release]; // 忘記這行 → 洩漏

// ARC 環境 (自動管理)
UIView *view = [[UIView alloc] init];
// ... 使用 view
[self.view addSubview:view];
// 無需 release,編譯器在作用域結束自動插入

ARC 避免不了的洩漏場景

  1. Block 循環引用:__weak typeof(self) weakSelf = self; 在 block 內使用 weakSelf
  2. 委派/代理循環:@property (nonatomic, weak) id delegate;
  3. CoreFoundation 對象:非 OC 物件,需手動 CFRetain/CFRelease 或 __bridge_transfer
  4. NSTimer/Target-Action 循環:Timer 持有 target,target 持有 timer → invalidate 時機把控

學習資源

  • Apple 官方 Transitioning to ARC
  • Matthijs Hollemans "ARC Tutorial" (RayWenderlich)
  • "8 Myths About ARC" — 打破常見誤區

2. 在適當情況下使用 reuseIdentifier

機制原理

UITableView/UICollectionView 維護重用佇列。dequeueReusableCellWithIdentifier: 從佇列取出可用 Cell,無則按註冊的 Class/Nib 新建。

正確使用模式


// 1. 註冊 (viewDidLoad 中)
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
// 或註冊 Nib
[tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];

// 2. 取用與配置 (cellForRowAtIndexPath)
static NSString *CellID = @"CustomCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
[cell configureWithData:dataSource[indexPath.row]];
return cell;

iOS 6+ 新增重用對象

  • UITableViewHeaderFooterView — registerClass:forHeaderFooterViewReuseIdentifier:
  • UICollectionReusableView (Supplementary Views) — registerClass:forSupplementaryViewOfKind:withReuseIdentifier:

無 reuseIdentifier 代價

  • 每行 alloc/init → 大量物件分配/釋放 → CPU 尖峰 → 掉幀
  • 記憶體佔用隨列表長度線性增長
  • Cell 內複雜子視圖重複建構開銷極大

3. 盡可能將 View 設置為不透明

原理

GPU 合成時,opaque=YES 視圖直接覆蓋寫入 Framebuffer,無需讀取底層像素進行混合運算 (Blending)。混合開銷 = 讀取目標像素 + 計算 + 寫回。

設定方式


// 代碼
view.opaque = YES;
view.backgroundColor = [UIColor whiteColor]; // 必須有不透明背景色或圖片填滿

// Interface Builder
// Attributes Inspector → View → 勾選 Opaque

驗證工具

Xcode → Debug → View Debugging → Color Blended Layers

  • ■ 紅色 = 正在混合 (透明/半透明)
  • ■ 綠色 = 不透明 (最佳)

常見誤區

  • view.alpha = 1.0 ≠ opaque = YES:alpha=1 但背景透明/有透明子視圖仍需混合
  • 設定 opaque=YES 但實際有透明像素 → 顯示錯誤 (黑底/閃爍)

4. 避免臃腫的 XIB/Storyboard

問題表現

  • 啟動時載入大型 XIB 導致啟動延遲 > 1s
  • 記憶體瞬間飆升 (所有 View 同時實例化)
  • Git 合併衝突極難解決 (XML 結構變動大)
  • 編譯時間增加

拆分策略

策略適用場景實現方式
功能模組拆分 XIB複雜頁面、可複用區塊每個 Cell、Header、Section、彈窗獨立 .xib
純代碼佈局高效能列表、動態佈局程式化 Auto Layout (Anchor API / Masonry / SnapKit)
多 Storyboard + Reference大型專案、團隊並行按功能劃分 Storyboard,用 Storyboard Reference 連接
SwiftUI (iOS 13+)新專案、聲明式 UI跨平台、預覽即時、無合併衝突

5. 不要阻塞主執行緒

主執行緒職責

  • UI 繪製、佈局、渲染
  • 觸摸/手勢事件分發
  • RunLoop 處理 Timer、Source、Observer
  • UIKit 所有 API (非線程安全,必須主執行緒調用)

阻塞來源分類與對策

類型典型操作解決方案
網路 I/O同步請求、大檔下載NSURLSession 異步、背景下載任務
磁碟 I/O大檔讀寫、資料庫寫入DispatchQueue.global().async / Core Data 背景上下文
CPU 密集JSON 解析、圖片解碼、加密、排序GCD 後台佇列、vImage/Accelerate 框架加速
鎖競爭主執行緒等待背景鎖無鎖資料結構、減少共享狀態、優先級反轉預防

檢測工具

  • Instruments → Time Profiler:主執行緒佔用 > 16ms/幀 即掉幀
  • Instruments → Main Thread Checker:自動偵測非主執行緒調用 UIKit
  • Xcode → Debug → View Debugging → Color Hitches:視覺化掉幀

總結:五大核心技巧落地清單

  1. ✅ 全專案啟用 ARC,審查 Block/Delegate/CFObject 循環引用
  2. ✅ 所有 Table/Collection View 100% 使用 reuseIdentifier + registerClass/Nib
  3. ✅ 掃描 Color Blended Layers,關鍵視圖設 opaque=YES + 實心背景
  4. ✅ 拆分超過 200 行 / 50 個 View 的 XIB,改用代碼或模組化 XIB
  5. ✅ 審查所有同步網路/IO/計算調用點,全部遷移至背景佇列
copyright © 萬盛學電腦網 all rights reserved