ios基础之一天一道笔试题(1)

以下代码有问题吗,如何优化?

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];
     }
 }

猜你喜欢

转载自blog.csdn.net/weixin_33912445/article/details/86974649