ios基礎之一天一道筆試題(1)

weixin_33912445發表於2019-01-25

以下程式碼有問題嗎,如何優化?

for (int i = 0; i < 100000000000; i ++)  {
      NSString *string = @"Hello";
      string = [string stringByAppendingFormat:@"--%d",i];
      string = [string uppercaseString];
}

解析:
本題主要考察記憶體管理相關知識點,我們先看一下蘋果官方文件關於autoreleasePool使用的其中一條說明:

If you write a loop that creates many temporary objects.
You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.

此題正是根據這條說明而出,如果不使用autoreleasePool,隨著迴圈次數的增加,程式執行的記憶體開銷會越來越大,直到程式記憶體溢位,文件中也給出了優化方案,即在迴圈內新增aotureleasePool以減少記憶體峰值,優化後的程式碼如下:

for (int i = 0; i < 1000000000; i ++) {
     @autoreleasepool {
         NSString *string = @"Hello";
         string = [string stringByAppendingFormat:@"--%d",i];
         string = [string uppercaseString];
     }
 }

相關文章