美文网首页
iOS autoreleasepool

iOS autoreleasepool

作者: CaptainRoy | 来源:发表于2019-05-24 22:38 被阅读0次
    • 一般当有处理大量临时对象时,如果不注意会造成内存暴增,可以使用 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 
    

    相关文章

      网友评论

          本文标题:iOS autoreleasepool

          本文链接:https://www.haomeiwen.com/subject/gbrozqtx.html