NSDateFormatter之性能优化

2 篇文章 0 订阅
1 篇文章 0 订阅

NSDateFormatter之性能优化

NSDateFormatter在开发过程使用算是频繁的,但是过度的创建NSDateFormatter用于NSDate与NSString之间格式转换,会导致App卡顿(特别是Cell上使用)。据官方NSDateFormatter官方文档说法,创建NSDateFormatter代价是比较高的,如果你使用的非常频繁,那么建议你缓存起来,缓存NSDateFormatter一定能提高效率。

测试性能Demo NSDateFormatterDemo
这里写图片描述

iOS7之前

在iOS 7之前,NSDateFormatter是非线程安全的,因此可能就会有两条或以上的线程同时访问同一个日期格式化对象,从而导致App崩溃,所以优化如下:

+ (NSDateFormatter *)cachedDateFormatter{
  NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
  NSDateFormatter *dateFormatter= [threadDictionary objectForKey:@"cachedDateFormatter"];
  if(!dateFormatter){
  dateFormatter= [[NSDateFormatter alloc]init];
  [dateFormatter setLocale:[NSLocale currentLocale]];
  [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
  [threadDictionary setObject:dateFormatter forKey:@"cachedDateFormatter"];
  }
  returndateFormatter;
  }
iOS7之后

NSDateFormatter都是线程安全的,因此我们无需担心日期格式化对象在使用过程中被另外一条线程给修改,为了提高性能,我们还可以在上述代码块中进行简化(除去冗余部分):

static NSDateFormatter *cachedDateFormatter= nil;
  + (NSDateFormatter *)cachedDateFormatter{
  if(!dateFormatter){
  dateFormatter= [[NSDateFormatter alloc]init];
  [dateFormatter setLocale:[NSLocale currentLocale]];
  [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
  }
  return dateFormatter;
  }

或者可以使用单例

+ (NSDateFormatter *)sharedDateFormatter
{
    static NSDateFormatter *_sharedDateFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        [formatter setLocale:[NSLocale currentLocale]];
        _sharedDateFormatter = formatter;
    });
    return _sharedDateFormatter;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值