2

I have 20 lines of code that replaces multiple values of NSString as below.

[resultstring
    replaceOccurrencesOfString:@"&"
    withString:@"&"
    options:NSLiteralSearch
    range:NSMakeRange(0, [resultstring length])
];

The problem is that it is takes some noticeable amount of time (20ms) for executing the code. Is there any better approach to write the NSString replacement code.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
ram
  • 95
  • 1
  • 5

1 Answers1

2

replaceOccurrencesOfString:... will traverse the string each time you call it.

An alternative which should make the replacement faster is to manually traverse the string just once and build a new string along the way.

Here's an example, although there's probably still room for further optimization

- (NSString *)encodeEntity:(NSString *)string {
    NSUInteger length = string.length;
    NSMutableString *encodedString = [NSMutableString stringWithCapacity:length];
    unichar buffer[length + 1];
    [string getCharacters:buffer range:(NSRange){0, length}];
    for(NSUInteger i = 0; i < length; i++) {
        char current = buffer[i];
        switch(current) {
            case '&':  [encodedString appendString:@"&amp;"];        break;
            case '\"': [encodedString appendString:@"&quot;"];       break;
            case '\'': [encodedString appendString:@"&apos;"];       break;
            case '<':  [encodedString appendString:@"&lt;"];         break;
            case '>':  [encodedString appendString:@"&gt;"];         break;
            default:   [encodedString appendFormat:@"%c", current];  break;
        }
    }
    return encodedString;
}

Also if your specific issue is to escape XML entities, this question may be useful: Objective C HTML escape/unescape

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235