我该如何优化这个循环?
我有一段代码返回一个代表“搜索结果”的超长字符串。每个结果都由双 HTML 中断符号表示。例如:
结果1
结果2
结果3
我有以下循环,它获取每个结果并将其放入数组中,去掉中断指示器,“kBreakIndicator
”(
)。问题是这个 lopp 的执行时间太长。有几个结果还好,但一旦达到一百个结果,速度就会慢大约 20-30 秒。这是不可接受的表现。我可以做些什么来提高性能?
这是我的代码:
content
是原始的 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];
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以做的是首先使用
NSString
的componentsSeparatedByString:
方法,该方法将为您提供一个NSArray
,如下所示:编辑:假设您的
kBreakIndicator
常量为
:@invariant 答案的结果:http://cl.ly/3Z112M3z3K1V2t0A3N2L
我的回答结果: http://cl.ly/371b2j2H0Y1E110D2w0I
如果您的
kBreakIndicator
常量是:
What you can do is first use
NSString
'scomponentsSeparatedByString:
method that will give you anNSArray
, like this:EDIT: Assuming your
kBreakIndicator
constant is<br>
:Result of @invariant's answer: http://cl.ly/3Z112M3z3K1V2t0A3N2L
Result of my answer: http://cl.ly/371b2j2H0Y1E110D2w0I
If your
kBreakIndicator
constant is<br><br>
:这应该可以做到:
This should do it: