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版本界面基本都换了一遍,现在主要任务是优化代码,封装再封装,寻求新技术。最近由于老版本造成的褥羊毛现象较为严重,正在努力解决。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IOT_Elon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值