I’m experiencing some abnormally high CPU usage values when running a certain piece of code in my application. According to Instruments, NSString‘s rangeOfString: method causes this. I do use this method very frequently in various for loops because I really have to.
My question is: How can I solve this? Instruments can tell me where about the issue lies, but this code is in a separate framework, so this is limited. Even though I know rangeOfString: causes it, I don’t know how to get around that with a more CPU preserving alternative.
This is the code that causes these problems:
- (NSArray *)resultStrings
{
NSMutableArray*_output = [[NSMutableArray alloc] init];
UsageHistory*_history = [[UsageHistory alloc] init];
NSHTTPCookieStorage*storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray*UsageHistoryArray = [[NSArray alloc] initWithArray:[_history usageHistory]];
NSArray*_storageCookies = [[NSArray alloc] initWithArray:[storage cookies]];
for (DAHistoryObject*object in UsageHistoryArray)
{
for (NSHTTPCookie*ck in _storageCookies)
{
@autoreleasepool
{
NSString*domain = [ck domain];
if ([[[ck domain] substringToIndex:1] isEqualToString:@"."])
{
domain = [[ck domain] stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""];
}
if ([[object url] rangeOfString:domain].location != NSNotFound)
{
NSHTTPCookie*cookie = [DAHTTPCookie createCookieWithURL:[ck domain] cookieName:[ck name] expires:[[ck expiresDate] timeIntervalSince1970] cookieValue:[ck value] browserType:DARavenBrowser secure:[ck isSecure]];
[_output addObject:cookie];
}
}
}
}
[UsageHistoryArray release];
[_storageCookies release];
[_history release];
return [_output autorelease];
}
With the disclaimer that optimizations are always compromises, it seems to me that you could gain something from doing the test only on the host name part of the history url. No need to search the whole url string when you are really just interested in the host name part – and the current method could actually be a subtle bug (if the domain name somehow matches the path name part of the url, for instance).
This should already provide some improvement.
Second, you could try just to match the cookie’s domain string against the end of the host name, but not sure if the added work to do that would improve performance.