关于oc中遍历的效率算法研究
在oc中,编写程序最常用的的算法莫过于对算法的遍历,下面我们来探索一下最常用的几种算法的效率。
-
for(int i = 0; ; )
-
for in
-
enumerateObjectsUsingBlock
-
dispatch_apply
-
NSPredicate
for(int i = 0; ; )
-(void)test {
for (int i = 0 ; i < self.arrData.count ; i ++) {
PersonModel *model = self.arrData[i];
NSLog(@"==========%@",model.name);
}
}
for in
int i = 0 ;
for ( PersonModel * model in self.arrData) {
i++;
NSLog(@"==========%@",model.name);
}
enumerateObjectsUsingBlock
-(void)test2 {
[self.arrData enumerateObjectsUsingBlock:^(PersonModel* model, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"==========%@",model.name);
}];
}
dispatch_apply
-(void)test3 {
dispatch_apply(self.arrData.count, dispatch_get_global_queue(0, 0), ^(size_t i) {
PersonModel *model = self.arrData[i];
NSLog(@"==========%@",model.name);
});
}
NSPredicate
-(void)test4 {
NSPredicate*predicate = [NSPredicate predicateWithFormat:@"name == 'sws1000'"];
NSMutableArray*arr = [self.arrData mutableCopy];
[arr filterUsingPredicate:predicate];
PersonModel*model = self.arrData[0];
NSLog(@"===============%@",model.name);
}
调用方法
- (IBAction)startBtn:(UIButton *)sender {
uint64_t begin = mach_absolute_time();
switch (self.type) {
case 0:
[self test ];
break;
case 1:
[self test1 ];
break;
case 2:
[self test2 ];
break;
case 3:
[self test3 ];
break;
case 4:
[self test4 ];
break;
default:
break;
}
uint64_t end = mach_absolute_time();
_timeLabel.text = [NSString stringWithFormat:@"用时%.9fs",pow(10,-9)*(end - begin)];
}
结论
我们分别对大小为10000和100000的数据进行遍历,发现,for(int i = 0; ; )耗时分别为:3.479707737s和29.039399192s;for in耗时分别为:3.409268507s和16.015781127;enumerateObjectsUsingBlock耗时分别为:3.423908732s和23.985882636s;dispatch_apply耗时分别为:1.958693214s和14.826218417s;NSPredicate耗时分别为:0.006494015s和0.046621182s。
从而得出结论,当数组很小时,并且数组存储的对象类型进行过滤操作时,NSPredicate的效率超乎想象的高,其次是在处理比较耗时的操作时gcd的多线程处理效果更高,其次是for in的处理方式。
点击链接进入观看完整代码。具体请参考: https://github.com/tianjifou/SWSErgodicArrayTest.git;(转载请说明出处,谢谢!)
网友评论