Nathan Fraenkel
Nathan Fraenkel

Reputation: 3462

Speed: iOS Using NSPredicate filterUsingPredicate vs. for loop

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!

Upvotes: 3

Views: 2439

Answers (1)

adpalumbo
adpalumbo

Reputation: 3031

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.

Upvotes: 2

Related Questions