My application read all people in contact in two ways:
for-loop:
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent ();
long count = macContact.addressBook.people.count;
for(int i=0;i<count;++i){
ABPerson *person = [macContact.addressBook.people objectAtIndex:i];
NSLog(@"%@",person);
}
NSLog(@"%f",CFAbsoluteTimeGetCurrent() - startTime);
for-each
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent ();
for(ABPerson *person in macContact.addressBook.people){
NSLog(@"%@",person);
}
NSLog(@"%f",CFAbsoluteTimeGetCurrent() - startTime);
for-each only took 4 seconds to enumerate 5000 people in addressBook, while for-loop took 10 minutes to do the same job.
I want to know why there is a huge difference in performance?
The difference in performance almost certainly has to do with the
macContact.addressBook.peoplepart. You’re calling that every single time through the for loop but only once with the for-each loop. I’m guessing either theaddressBookor thepeopleproperties are not returning cached data but rather new data every time.Try using
You’ll probably find the performance is very similar again.
That said, for-each is faster than for in general. The reason is because a for loop invokes a method send on every single pass through the loop (
-objectAtIndex:), whereas for-each can fetch the objects much more efficiently by grabbing them in large batches.In more recent versions of the OS you can go a step further and use a block-based enumeration method. This looks like
For NSArrays this should have very similar performance to a for-each loop. For other data structures such as dictionaries this style can be faster because it can fetch the value along with the key (whereas a for-each only gives you the key and requires you to use a message send to get the value).