效能是蘋果審核時相當看重的一環。CPU 佔用、記憶體、圖形繪製、儲存空間、網路表現,每一項都是 App 品質的組成部分。無論你是獨立開發者還是企業團隊的一員,都該牢記一個原則:站在使用者角度看問題。
最典型的例子就是介面適配。不同機型不該造成嚴重的版面落差;操作過程不該出現肉眼可見的卡頓;最糟的情況則是閃退——而閃退幾乎等同於被刪除,屬於最嚴重的問題等級。
Instruments 是目前最強大的效能診斷工具之一,內建了記憶體管理、I/O、網路等多種檢測儀表。本文聚焦兩個最常用的:Allocations 與 Time Profiler。
我們用一個「逐字把文字印到畫面上」的極端範例來製造記憶體壓力。剛開始跑起來還算順,但很快你就会發現速度像蝸牛一樣,而且千萬別跑太久,否則記憶體會直接被吃乾。
@implementation FETextView
- (id)initWithFrame:(CGRect)frame text:(NSString *)text {
self = [super initWithFrame:frame];
if (self) {
// 每 0.01 秒觸發一次,累積效應非常可觀
[NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(appendNextCharacter)
userInfo:nil
repeats:YES];
_text = [text copy];
self.backgroundColor = [UIColor whiteColor];
}
return self;
}
// 每一次呼叫,都把「到目前為止」的所有字元重新建立成 label
- (void)appendNextCharacter {
for (NSUInteger i = 0; i <= self.index; i++) {
if (i < self.text.length) {
UILabel *label = [[UILabel alloc] init];
label.text = [self.text substringWithRange:NSMakeRange(i, 1)];
label.opaque = NO;
[label sizeToFit];
CGRect frame = label.frame;
frame.origin = [self originAtIndex:i fontSize:label.font.pointSize];
label.frame = frame;
[self addSubview:label]; // 舊 label 從來沒有被移除
}
}
self.index++;
}
// 遞迴計算每個字元該放的位置
- (CGPoint)originAtIndex:(NSUInteger)index fontSize:(CGFloat)fontSize {
if (index == 0) {
return CGPointZero;
}
CGPoint origin = [self originAtIndex:index - 1 fontSize:fontSize];
NSString *prevCharacter = [self.text substringWithRange:NSMakeRange(index - 1, 1)];
CGSize prevCharacterSize = [prevCharacter sizeWithAttributes:@{
NSFontAttributeName: [UIFont systemFontOfSize:fontSize]
}];
origin.x += prevCharacterSize.width;
if (origin.x > CGRectGetWidth(self.bounds)) {
origin.x = 0;
origin.y += prevCharacterSize.height;
}
return origin;
}
@end
主視圖控制器只需要把文字檔讀進來,交給這個 view:
NSString *path = [[NSBundle mainBundle] pathForResource:@"FlyElephant" ofType:@"txt"];
FETextView *textView = [[FETextView alloc]
initWithFrame:CGRectMake(0, 64,
CGRectGetWidth(self.view.bounds),
CGRectGetHeight(self.view.bounds))
text:[NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil]];
[self.view addSubview:textView];
把 Instruments 的 Allocations 儀表掛上去跑一輪,會看到記憶體曲線一路向上、幾乎沒有回落。原因其實很直白:
removeFromSuperview,節點數量呈等比級數成長。originAtIndex: 是遞迴實作,每次都要重算前面所有字元,時間複雜度同樣不理想。正確做法是把 label 建立一次、之後只更新文字;位置則用一次遍歷累加記錄,避免重複遞迴;計時器間隔也該對齊畫面的更新節奏。
Allocations 回答「記憶體去哪了」,Time Profiler 回答的則是「時間去哪了」。它會週期性地擷取主執行緒的呼叫堆疊,並依樣本數排序,讓你一眼看出哪個函式佔用了最多 CPU。
使用上的關鍵提醒:
一句總結:效能優化不是憑感覺猜,而是先用 Instruments 量到證據,再針對最重的那一項下手。