Optimizing a loop
Optimizing a loop
- Subject: Optimizing a loop
- From: "Eric E. Dolecki" <email@hidden>
- Date: Tue, 19 Jul 2011 08:52:39 -0400
I have an NSMutableArray that contains a MPMediaItem and song title as it's
key.
I then take a search string and loop through the entire NSMutableArray
looking for a fuzzy match. It works very well, the problem is that the array
contains 1,777 items (could contain more) and the search takes about 6
seconds on iOS. I am wondering how I could optimize this to get the search
time down. I was thinking of splitting the array into 2 or something, just
not really sure what the best approach might be.
Here is some code I am using (stringValue passed in through the method):
@autoreleasepool {
float currentFoundValue = 1000.0;
MPMediaItem *test;
NSArray *dis;
MPMediaItemCollection *collection;
float match;
* //This takes about 6 seconds each search for song*
for (id key in songsDictionary) {
NSString *thisSong = key;
int suppliedCount = [stringValue length];
int keyCount = [thisSong length];
//Fuzzy matching
if(suppliedCount > keyCount){
match= [StringDistance stringDistance:thisSong
:stringValue];
} else {
match= [StringDistance stringDistance:stringValue
:thisSong];
}
//Get the very best match there is to be found for song.
if(match < currentFoundValue){
currentFoundValue = match;
test = [songsDictionary objectForKey:thisSong];
dis = [NSArray arrayWithObject:test];
collection = [[MPMediaItemCollection alloc]
initWithItems:dis];
}
}
if([collection count] != 0){
[musicPlayer setQueueWithItemCollection:collection];
[musicPlayer play];
//Used to populate a UITableView
songsArray = [[NSMutableArray alloc] init];
@autoreleasepool {
for (MPMediaItem *song in dis) {
NSString *title = [song
valueForProperty:MPMediaItemPropertyTitle];
[songsArray addObject:title];
}
}
[myTable reloadData];
[myTable flashScrollIndicators];
countView.hidden = NO;
countLabel.text = [NSString stringWithFormat:@"%d",
[songsArray count]];
} else {
NSString *msg = [NSString stringWithFormat:@"Search could
not find the song \"%@\". Please try again.", stringValue];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Song
Not Found"
message:msg
delegate:self
cancelButtonTitle:@
"OK"
otherButtonTitles:nil];
[alert show];
}
}
Thanks for any suggestions.
- Eric
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden