【发布时间】:2019-03-12 16:56:51
【问题描述】:
有人告诉我,循环中的 @autoreleasepool 块可以减少内存使用的峰值,直到我进行测试。测试设备为 iOS 11.4.1 的 iPhone 6s。
我的代码:
@implementation BigMemObj{
NSMutableArray *_mutArr;
}
-(instancetype)init{
if(self = [super init]){
_mutArr = [[NSMutableArray alloc] initWithCapacity:1024*1024*30];
for(int i = 0; i < 1024*1024*30; i++){
[_mutArr addObject:@(i)];
}
}
return self;
}
- (void)viewDidLoad {
NSMutableArray *arr = [[NSMutableArray alloc] init];
for(int i = 0 ; i < 10000; i++){
@autoreleasepool {
BigMemObj *mem = [[BigMemObj alloc] init];
}
}
}
- (void)viewDidLoad {
NSMutableArray *arr = [[NSMutableArray alloc] init];
for(int i = 0 ; i < 10000; i++){
BigMemObj *mem = [[BigMemObj alloc] init];
}
}
我运行这两个测试 34 秒,在测试 1 中,最高内存使用量为 458M,但在测试 2 中,最高内存使用量为 362M。并且两个测试都是三角形。
使用@autorelaspool 块
autoreleasepool 的实现是否发生了变化?还是编译器做了一些优化?
谢谢!
【问题讨论】:
-
ARC在使用对象的block完成后自动释放对象,所以不需要手动使用@autoreleasepool。
标签: ios nsautoreleasepool