以下代碼有問題嗎,如何優(yōu)化?
for (int i = 0; i < 100000000000; i ++) {
NSString *string = @"Hello";
string = [string stringByAppendingFormat:@"--%d",i];
string = [string uppercaseString];
}
解析:
本題主要考察內(nèi)存管理相關(guān)知識點,我們先看一下蘋果官方文檔關(guān)于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.
此題正是根據(jù)這條說明而出派撕,如果不使用autoreleasePool,隨著循環(huán)次數(shù)的增加,程序運行的內(nèi)存開銷會越來越大荒叶,直到程序內(nèi)存溢出,文檔中也給出了優(yōu)化方案,即在循環(huán)內(nèi)添加aotureleasePool以減少內(nèi)存峰值愚墓,優(yōu)化后的代碼如下:
for (int i = 0; i < 1000000000; i ++) {
@autoreleasepool {
NSString *string = @"Hello";
string = [string stringByAppendingFormat:@"--%d",i];
string = [string uppercaseString];
}
}