首页 > 代码库 > 高效的把NSMutableArray变成NSArray

高效的把NSMutableArray变成NSArray

高效的把NSMutableArray变成NSArray

我们在方法内部可能会用NSMutableArray,但是返回的时候希望其他人不去改我们的Array

   NSMutableArray *array1 = [@[] mutableCopy];
    for (int i = 0; i < 10000000; i++)
    {
        [array1 addObject:@(i)];
    }

    return array1;

这个时候我们通常的做法是拷贝array1或者是生成一个新的array1

return [array1 copy];
return [NSArray arrayWithArray:array1];

这里呢,我们打印了下时间

    NSMutableArray *array1 = [@[] mutableCopy];
    NSMutableArray *array2 = [@[] mutableCopy];

    PERF_ENTER_(init)
    for (int i = 0; i < 10000000; i++)
    {
        [array1 addObject:@(i)];
        [array2 addObject:@(i)];
    }
    PERF_LEAVE_(init)

    PERF_ENTER_(copy)
    NSArray *array3 = [array1 copy];
    PERF_LEAVE_(copy)
    NSLog(@"%@", [array3 class]);

    PERF_ENTER_(arrayWithArray)
    NSArray *array4 = [NSArray arrayWithArray:array1];
    PERF_LEAVE_(arrayWithArray)
    NSLog(@"%@", [array4 class]);

/*    
2015-01-07 00:57:36.869 JoinShow[1134:68543] +[XYPerformance recordName:andTime:] 'init' = 5.492105(s)
2015-01-07 00:57:37.125 JoinShow[1134:68543] +[XYPerformance recordName:andTime:] 'copy' = 0.255650(s)
2015-01-07 00:57:37.125 JoinShow[1134:68543] __NSArrayI
2015-01-07 00:57:37.373 JoinShow[1134:68543] +[XYPerformance recordName:andTime:] 'arrayWithArray' = 0.247696(s)
2015-01-07 00:57:37.373 JoinShow[1134:68543] __NSArrayI
*/

发现正常拷贝一个大array需要0.2s,这已经是不能忍的时间了.需要对方法进行优化.

问题的本质是什么,是我们需要返回一个不可变的array,因此我们可以直接把 NSMutableArray 对象的isa 修改成 NSArray.

- (NSArray *)immutable
{
    object_setClass(self, [NSArray class]);
    return self;
}

    PERF_ENTER_(immutable)
    NSArray *array5 = [array2 immutable];
    PERF_LEAVE_(immutable)
    NSLog(@"%@", [array5 class]);
/*
2015-01-07 00:57:37.373 JoinShow[1134:68543] +[XYPerformance recordName:andTime:] 'immutable' = 0.000030(s)
2015-01-07 00:57:37.373 JoinShow[1134:68543] NSArray
*/

看下时间,果然快很多.

高效的把NSMutableArray变成NSArray