How can I optimize this loop?
        Posted  
        
            by 
                Moshe
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Moshe
        
        
        
        Published on 2010-12-25T23:42:55Z
        Indexed on 
            2010/12/25
            23:53 UTC
        
        
        Read the original article
        Hit count: 254
        
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] autorelease];
   }
  }
//Do something with the results array.
[results release];
© Stack Overflow or respective owner