我上具有使用Web服務和核心數據在一個緊密的循環同步過程中的iPad應用工作。根據Apple's Recomendation我分配減少內存佔用和週期性漏極的NSAutoreleasePool
。這目前效果很好,目前的應用程序沒有內存問題。但是,我打算轉移到ARC,因爲NSAutoreleasePool
不再有效,並希望保持這種相同的性能。我創建了幾個例子和定時他們我想知道什麼是最好的方法,使用ARC,以acheive同類性能和維護代碼的可讀性。降低峯值內存使用@autoreleasepool
出於測試目的,我想出了3個場景,每個創建使用1和10,000,000之間的數字的字符串。我跑了每個示例3次,以確定他們是否使用與蘋果LLVM編譯器3.0在Mac 64位應用程序所用的時間(W/O GDB -O0)和XCode的4.2。我還通過儀器運行每個示例來大致瞭解記憶峯值。
以下每個都包含在下面的代碼塊中的例子:
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSDate *now = [NSDate date];
//Code Example ...
NSTimeInterval interval = [now timeIntervalSinceNow];
printf("Duration: %f\n", interval);
}
}
NSAutoreleasePool批次[原件預ARC](峯值記憶:〜116 KB)
static const NSUInteger BATCH_SIZE = 1500;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for(uint32_t count = 0; count < MAX_ALLOCATIONS; count++)
{
NSString *text = [NSString stringWithFormat:@"%u", count + 1U];
[text class];
if((count + 1) % BATCH_SIZE == 0)
{
[pool drain];
pool = [[NSAutoreleasePool alloc] init];
}
}
[pool drain];
運行時間:
10.928158
10.912849
11.084716
外@autoreleasepool(峯值存儲器:〜382 MB)
@autoreleasepool {
for(uint32_t count = 0; count < MAX_ALLOCATIONS; count++)
{
NSString *text = [NSString stringWithFormat:@"%u", count + 1U];
[text class];
}
}
運行時間:
11.489350
11.310462
11.344662
內@autoreleasepool(峯值記憶:〜61.2KB)
for(uint32_t count = 0; count < MAX_ALLOCATIONS; count++)
{
@autoreleasepool {
NSString *text = [NSString stringWithFormat:@"%u", count + 1U];
[text class];
}
}
運行時間:
14.031112
14.284014
14。099625
@autoreleasepool瓦特/ GOTO(峯值存儲器:〜115KB)
static const NSUInteger BATCH_SIZE = 1500;
uint32_t count = 0;
next_batch:
@autoreleasepool {
for(;count < MAX_ALLOCATIONS; count++)
{
NSString *text = [NSString stringWithFormat:@"%u", count + 1U];
[text class];
if((count + 1) % BATCH_SIZE == 0)
{
count++; //Increment count manually
goto next_batch;
}
}
}
運行時間:
10.908756
10.960189
11.018382
的goto
聲明提供最接近的性能,但它採用的是goto
。有什麼想法嗎?
更新:
注:goto
聲明是在documentation表示不會泄漏內存的@autoreleasepool一個正常的退出。
在進入時,會推送自動釋放池。在正常退出(中斷, 返回,轉到,通過,等等)自動釋放池被彈出。 爲了與現有代碼兼容,如果退出是由於例外造成的,則 自動釋放池不會彈出。
使用優化。這對ARC代碼來說非常重要。 – 2012-03-12 21:58:20
因此'goto'肯定不是,我不知道,導致內存泄漏?其他一切都合情合理:減少排水速度更快。無論如何,我只能評論可讀性:在任何你游泳池都很好。那個goto需要一個黃色的粘滯便箋。 – 2012-03-12 21:58:42
goto似乎沒有泄漏任何內存。看起來像我期望的那樣排除了autorelease池的範圍,但我不是ARC的專家(還),並且不想依賴UB。 – Joe 2012-03-12 22:07:06