Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your algorithm is not very good. For each tag you try to remove it, even if it is stripped already. Also each iteration of the loop causes a copy of the whole HTML string to be made, often without even stripping out anything. If you are not using ARC those copies also will persist until the current autorelease pool gets popped. You are not only wasting memory, you also do a lot of uneccessary work.</p> <p>Testing your method (with the Cocoa wikipedia article) takes 3.5 seconds.</p> <p>Here is an improved version of this code:</p> <pre><code>- (NSString *)flattenHTML:(NSString *)html { NSScanner *theScanner = [NSScanner scannerWithString:html]; theScanner.charactersToBeSkipped = nil; NSMutableString *result = [NSMutableString stringWithCapacity: [html length]]; while (![theScanner isAtEnd]) { NSString *part = nil; if ([theScanner scanUpToString:@"&lt;" intoString: &amp;part] &amp;&amp; part) { [result appendString: part]; } [theScanner scanUpToString:@"&gt;" intoString:NULL]; [theScanner scanString: @"&gt;" intoString: NULL]; } return [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; } </code></pre> <p>This will tell the scanner to get every character up to the first <code>&lt;</code> and append them to the result string if there are any. Then it will skip up to the next <code>&gt;</code> and then also skip the <code>&gt;</code> to strip out the tag. This will get repeated until the end of the text. Every character is only touched once making this an <code>O(n)</code> algorithm.</p> <p>This takes only 6.5 ms for the same data. That is about 530 times faster.</p> <p>Btw, those measurements where made on a Mac. The exact values will of course be different on an iPhone.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload