美文网首页
NSDateFormatter 优化

NSDateFormatter 优化

作者: Harry_Lee | 来源:发表于2017-12-01 16:17 被阅读9次

localtime替代NSDateFormatter来完成NSDateNSString的转换

Gist

  • 测量代码
- (void)testDateFormatter {
    NSDate *date = [NSDate date];
    
    uint64_t t1 = dispatch_benchmark(10000, ^{
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd";
        NSString *dateString = [fmt stringFromDate:date];
        //NSLog(@"%@", dateString);
    });

    uint64_t t2 = dispatch_benchmark(10000, ^{
        time_t timeInterval = [date timeIntervalSince1970];
        struct tm *cTime = localtime(&timeInterval);
        NSString *dateString = [NSString stringWithFormat:@"%d-%02d-%02d",cTime->tm_year+1900,
                                cTime->tm_mon+1,cTime->tm_mday];
        //NSLog(@"%@", dateString);
    });
    
    NSLog(@"t1:%llu, t2:%llu", t1, t2);
}
  • 输出
t1:65482, t2:17860
t1:64783, t2:16978
t1:64048, t2:16813
t1:63576, t2:18177
t1:63270, t2:16066
  • localtimeNSDateFormatter相比较性能方面有大约73%左右的提升。

相关文章

网友评论

      本文标题:NSDateFormatter 优化

      本文链接:https://www.haomeiwen.com/subject/zqewbxtx.html