高效的把NSMutableArray变成NSArray
发表时间:2020-11-5
发布人:葵宇科技
浏览次数:23
下效的把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 */
看下光阳,出有雅然快很多.
-----------------
闭于那多么做,咱只能道念法想法是好的.实际...