本文精選自 25 條 iOS 效能優化建議中的前 5 條核心技巧,針對記憶體管理、列表重用、GPU 混合優化、介面載入速度、執行緒模型進行深度解析,並提供可直接落地的代碼模式與檢測方法。
retain/release/autorelease,消除人為疏漏dealloc 手寫錯誤風險
// 手動管理 (易忘 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,編譯器在作用域結束自動插入
__weak typeof(self) weakSelf = self; 在 block 內使用 weakSelf@property (nonatomic, weak) id delegate;CFRetain/CFRelease 或 __bridge_transferUITableView/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;
UITableViewHeaderFooterView — registerClass:forHeaderFooterViewReuseIdentifier:UICollectionReusableView (Supplementary Views) — registerClass:forSupplementaryViewOfKind:withReuseIdentifier:alloc/init → 大量物件分配/釋放 → CPU 尖峰 → 掉幀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 但實際有透明像素 → 顯示錯誤 (黑底/閃爍)| 策略 | 適用場景 | 實現方式 |
|---|---|---|
| 功能模組拆分 XIB | 複雜頁面、可複用區塊 | 每個 Cell、Header、Section、彈窗獨立 .xib |
| 純代碼佈局 | 高效能列表、動態佈局 | 程式化 Auto Layout (Anchor API / Masonry / SnapKit) |
| 多 Storyboard + Reference | 大型專案、團隊並行 | 按功能劃分 Storyboard,用 Storyboard Reference 連接 |
| SwiftUI (iOS 13+) | 新專案、聲明式 UI | 跨平台、預覽即時、無合併衝突 |
| 類型 | 典型操作 | 解決方案 |
|---|---|---|
| 網路 I/O | 同步請求、大檔下載 | NSURLSession 異步、背景下載任務 |
| 磁碟 I/O | 大檔讀寫、資料庫寫入 | DispatchQueue.global().async / Core Data 背景上下文 |
| CPU 密集 | JSON 解析、圖片解碼、加密、排序 | GCD 後台佇列、vImage/Accelerate 框架加速 |
| 鎖競爭 | 主執行緒等待背景鎖 | 無鎖資料結構、減少共享狀態、優先級反轉預防 |