IOS-66-NSDateFormatter性能优化

NSDateFormatter多次创建是很耗性能的,比如创建10240次,会花费3.4秒的时间,下面介绍三种创建方法,推荐用第三种:
1.普通创建方法:

// 原生方法转换日期  3.396087秒
- (void)convertDateByDateFormatter{
    double then = CFAbsoluteTimeGetCurrent();
    for (int i=0; i<10240; i++) {
        NSDateFormatter *newDate = [[NSDateFormatter alloc] init];
        [newDate setDateFormat:@"yyyy-MM-dd"];
        [newDate setTimeZone:self.timeZone];
        self.dateStr = [newDate stringFromDate:[NSDate date]];
    }
    double now = CFAbsoluteTimeGetCurrent();
    NSLog(@"DateFormatter:%f",now-then);
}

2.c语言方法转换日期 0.095040秒

- (void)convertDateByCLocaltime{
    double then = CFAbsoluteTimeGetCurrent();
    for (int i=0; i<10240; i++) {
        time_t timeInterval = [NSDate date].timeIntervalSince1970;
        struct tm *cTime = localtime(&timeInterval);
        _dateStr = [NSString stringWithFormat:@"%d-%02d-%02d", cTime->tm_year + 1900, cTime->tm_mon + 1, cTime->tm_mday];
    }
    double now = CFAbsoluteTimeGetCurrent();
    NSLog(@"CLocaltime:%f",now-then);
}

3.单例方法 0.186150秒

-(NSDateFormatter *)dateFormatter{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setTimeZone:self.timeZone];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }

    return _dateFormatter;
}

- (void)convertDateToStringUsingSingletonFormatter
{
    double then = CFAbsoluteTimeGetCurrent();
    for (NSUInteger i = 0; i < 10240; i++) {
        self.dateStr = [self.dateFormatter stringFromDate:[NSDate date]];
    }
    double now = CFAbsoluteTimeGetCurrent();
    NSLog(@"SingletonFormatter:%f", now - then);
}

demo地址:http://download.csdn.net/detail/iot_li/9589204

最近公司业务较稳定了,开发任务较少,目前是正在开发2.5.0版本、3.0版本,3.0版本界面基本都换了一遍,现在主要任务是优化代码,封装再封装,寻求新技术。最近由于老版本造成的褥羊毛现象较为严重,正在努力解决。

你可能感兴趣的:(iOS)