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;
}