优化此循环

时间:2013-02-08 18:26:23

标签: objective-c xcode optimization for-loop nsdateformatter

我正在仪器中运行时间分析器。我尽可能地简化了代码,将所有内容都归结为确切的问题。循环内部的代码行有checkInString = [_ formatter stringFromDate:[checkInArrayCopy objectAtIndex:i]];占用了90%的处理时间。关于如何优化此代码的任何想法?

 NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[format setDateFormat:@"MM/dd/YYYY"];
NSString *checkInString;
for (int x=0; x<100; x++) { 
    for (int i=0; i<checkInArray.count; i++) { //CheckInArray is a NSMutableArray of NSDates, with about 100 objects inside
        checkInString =[_formatter stringFromDate:[checkInArray objectAtIndex:i]]; //**90% of processing time
    }
}

3 个答案:

答案 0 :(得分:4)

说实话,我认为任何重大改进都将是算法更改,超出了我们在这里可以实际建议的范围(例如,减少您需要做的循环次数,或者无需获得所有日期的字符串)。

您可以做一些微优化,但我不认为它们会产生巨大的差异。基本上,您可以通过使用IMP缓存和NSArray的枚举方法而不是C for循环来减少邮件发送的数量,这应该会给予一点点提升。

NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[format setDateFormat:@"MM/dd/YYYY"];
__block NSString *checkInString;
id (*stringFromDateIMP)(id, SEL, id) = [_formatter methodForSelector:@selector(stringFromDate:)];
for (int x=0; x<100; x++) { 
    [checkInArray enumerateObjectsUsingBlock:^(NSDate *date, NSUInteger i, BOOL *stop) { //CheckInArray is a NSMutableArray of NSDates, with about 100 objects inside
        checkInString = stringFromDateIMP(_formatter, @selector(stringFromDate:), date);
    }];
}

(用浏览器编写,所以警告compilor 。)

答案 1 :(得分:2)

有明显的免责声明可能存在我完全错过的内容,当前代码会在相同的日期转换100次。

如果这是正确的,您只能通过一次转换获得很多收益。以下代码显示了原理,但请注意它是未经测试的,因此在阅读时请使用常识:

NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[format setDateFormat:@"MM/dd/YYYY"];

NSMutableArray *dates = [NSMutableArray array];
for (int i=0; i<checkInArray.count; i++) { //CheckInArray is a NSMutableArray of NSDates, with about 100 objects inside
    NSString *cis =[format stringFromDate:[checkInArray objectAtIndex:i]]
    [dates addObject: cis];
}

NSString *checkInString;
for (int x=0; x<100; x++) { 
    for (int i=0; i<checkInArray.count; i++) { 
        checkInString = [dates objectAtIndex:i]; 
    }
}

代码维护您对objectAtIndex:的使用,您可能希望使用foreach或阻止来执行循环,但这是一个细节。

答案 2 :(得分:1)

你的for循环非常简单。你真正想要的是stringFromDate方法本身的优化......

检查出来

What are some possible optimizations for NSDateFormatter's stringFromDate?

我认为你无能为力。格式化操作将占用一些CPU ...除非您可以根据您对输入值的任何假设来设计自己的算法