Reputation: 81
I have an NSArray called 'objects' below with arrayCount = 1000. It takes about 10 secs to iterate through this array. Does anyone have a faster method of iterating through this array?
for (int i = 0; i <= arrayCount; i++) {
event.latitude = [[[objects valueForKey:@"CLatitude"] objectAtIndex:i] floatValue];
event.longitude = [[[objects valueForKey:@"CLongitude"] objectAtIndex:i] floatValue];
}
Upvotes: 1
Views: 7708
Reputation: 1195
Adding to what others have said here, fast enumeration is faster because it iterates a C array, whereas accessing indices using objectAtIndex: has the overhead of Objective C object messaging. Think of it as asking the NSArray object for all of its stuff at once, as opposed to asking for each object individually.
The enumerateObjectsUsingBlock: method is nearly just as fast. Blocks can be powerful because you can assign a chunk of code to a variable and pass it around.
I was looking for actual benchmarks and found this:
http://darkdust.net/writings/objective-c/nsarray-enumeration-performance
Upvotes: 2
Reputation: 1160
The fastest way to iterate over an NSArray would be to use fast enumeration. I your case this would be:
for (id object in objects) {
event.latitude = [[object valueForKey:@"CLatitude"] floatValue];
event.longitude = [[object valueForKey:@"CLongitude"] floatValue]
}
Upvotes: 4
Reputation:
It looks like the arrays returned by valueForKey will be the same at every iteration so try obtaining a reference to them once outside the loop:
NSArray *latitudes = [objects valueForKey:@"CLatitude"];
NSArray *longitudes = [objects valueForKey:@"CLongitude"];
for (int i = 0; i <= arrayCount; i++) {
event.latitude = [[latitudes objectAtIndex:i] floatValue];
event.longitude = [[longitudes objectAtIndex:i] floatValue];
}
But what is the point of the loop? In the end, doesn't it just set the event properties to the last values in the two arrays? Also, if arrayCount is the number of elements then the loop should be up to i < arrayCount
instead of i <= arrayCount
.
Upvotes: 2