速度:iOS使用NSPredicate filterUsingPredicate与for循环 [英] Speed: iOS Using NSPredicate filterUsingPredicate vs. for loop

查看:231
本文介绍了速度:iOS使用NSPredicate filterUsingPredicate与for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要过滤一个自定义对象的NSMutableArray,并想知道下面的一个在速度/运行时方面是否比另一个更好,或者它们几乎是相同的:

(1)使用[array filterUsingPredicate:predicate],



(2)使用for循环遍历所有元素,并检查它们是否符合条件。



我只问这个,因为我认为每个对象都必须满足可能会有所不同,所以使谓语可能会非常棘手。



感谢提前!

解决方案我不会相信任何一种技术在一般情况下的速度会更快。这两种技术都将对如何编写循环或谓词以及数据的外观如此敏感。如果这个数组没有按照你的过滤标准进行排序,那么它们都只需要遍历所有的元素。



使用那个让你更清洁的更可维护的代码,然后考虑尝试并将其与另一种方法进行比较,如果您发现存在实际的性能瓶颈问题。


I need to filter an NSMutableArray of custom objects and was wondering about whether or not one of the following is BETTER than the other in terms of speed/runtime, or if they are virtually the same:

(1) Using [array filterUsingPredicate:predicate],

or

(2) Using a for loop to iterate through all elements and check if they satisfy the criteria or not myself.

I only ask this because I think the criteria each object must satisfy could vary so making the predicate could be tricky.

Thanks in advance!

解决方案

I wouldn't trust either technique to be meaningfully faster in the general case. Both techniques will be sensitive to how the loop or predicates are written, and what the data looks like. If the array is unsorted with respect to your filter criteria, they'll both just have to step through all the elements anyway.

Use the one that leaves you with cleaner and more maintainable code, and then consider trying and comparing it to the other approach if you see that there's an actual performance bottleneck.

这篇关于速度:iOS使用NSPredicate filterUsingPredicate与for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆