iOS autoreleasepool
2019-05-24 本文已影响0人
CaptainRoy
- 一般当有处理大量临时对象时,如果不注意会造成内存暴增,可以使用 autoreleasepool 进行优化
- 一下代码时计算内存使用情况
// 计算当前内存
double getMemoryUsage(void) {
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);
double memoryUsageInMB = kerr == KERN_SUCCESS ? (info.resident_size / 1024.0 / 1024.0) : 0.0;
return memoryUsageInMB;
}
- 比如如下创建大量对象
NSLog(@" 内存 - %f ",getMemoryUsage()); // 内存 - 73.328125
for (int i = 0; i < 500000; i++) {
NSNumber *num = [NSNumber numberWithInt:i];
NSString *str = [NSString stringWithFormat:@"%d ", i];
[NSString stringWithFormat:@"%@%@", num, str];
}
NSLog(@" 内存 - %f ",getMemoryUsage()); // 内存 - 95.750000
- 使用 autoreleasepool
NSLog(@" 内存 - %f ",getMemoryUsage()); // 内存 - 73.339844
for (int i = 0; i < 500000; i++) {
@autoreleasepool {
NSNumber *num = [NSNumber numberWithInt:i];
NSString *str = [NSString stringWithFormat:@"%d ", i];
[NSString stringWithFormat:@"%@%@", num, str];
}
}
NSLog(@" 内存 - %f ",getMemoryUsage()); // 内存 - 73.339844