How can I optimize this loop?
I've got a piece of code that returns a super-long string that represents "search results". Each result is represented by a double HTML break symbol. For example:
Result1<br><br>Result 2<br><br>Result3
I've got the following loop that takes each result and puts it into an array, stripping out the break indicator, "kBreakIndicator
" (<br><br>). The problem is that this lopp takes way too long to execute. With a few results it's fine, but once you hit a hundred results, it's about 20-30 seconds slower. It's unacceptable performance. What can I do to improve performance?
Here's my code:
content
is the original NSString.
NSMutableArray *results = [[NSMutableArray alloc] init];
//Loop through the string of results and take each result and put it into an array
while(![content isEqualToString:@""]){
NSRange rangeOfResult = [content rangeOfString:kBreakIndicator];
NSString *temp = (rangeOfResult.location != NSNotFound) ? [content substringToIndex:rangeOfResult.location] : nil;
if (temp) {
[results addObject:temp];
content = [[[content stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@%@", temp, kBreakIndicator] withString:@""] mutableCopy] autorelease];
}else{
[results addObject:[content description]];
content = [[@"" mutableCopy] autorel开发者_开发知识库ease];
}
}
//Do something with the results array.
[results release];
What you can do is first use NSString
's componentsSeparatedByString:
method that will give you an NSArray
, like this:
EDIT: Assuming your kBreakIndicator
constant is <br>
:
NSArray *temp_results = [content componentsSeparatedByString:kBreakIndicator];
NSMutableArray *results = [[NSMutableArray alloc] init];
for(NSString *result in temp_results) {
if(result.length == 0) continue;
[results addObject:result];
}
//do something with results...
[results release];
Result of @invariant's answer: http://cl.ly/3Z112M3z3K1V2t0A3N2L
Result of my answer: http://cl.ly/371b2j2H0Y1E110D2w0I
If your kBreakIndicator
constant is <br><br>
:
NSArray *result = [content componentsSeparatedByString:kBreakIndicator];
This should do it:
NSArray *results = [content componentsSeparatedByString:@"<br><br>"];
精彩评论