性能優(yōu)化之 NSDateFormatter

作者:tingxins
鏈接:http://m.itdecent.cn/p/82c1104aea6c#nsdateformatter
來源:簡書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

為什么要優(yōu)化NSDateFormatter?
首先,過度的創(chuàng)建NSDateFormatter用于NSDate與NSString之間轉(zhuǎn)換,會導致App卡頓,打開Profile工具查一下性能,你會發(fā)現(xiàn)這種操作占CPU比例是非常高的。據(jù)官方說法,創(chuàng)建NSDateFormatter代價是比較高的,如果你使用的非常頻繁,那么建議你緩存起來,緩存NSDateFormatter一定能提高效率。
優(yōu)化方式有哪些?

a.延遲轉(zhuǎn)換
即只有在UI需要使用轉(zhuǎn)換結(jié)果時在進行轉(zhuǎn)換。

b.Cache in Memory
根據(jù)NSDateFormatter線程安全性,不同的iOS系統(tǒng)版本內(nèi)存緩存如下:

prior to iOS 7
如果直接采用靜態(tài)變量進行存儲,那么可能就會存在線程安全問題,在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"];

}

return dateFormatter;

}

iOS 7 or later
在iOS 7、macOS 10.9及以上系統(tǒng)版本,NSDateFormatter都是線程安全的,因此我們無需擔心日期格式化對象在使用過程中被另外一條線程給修改,為了提高性能,我們還可以在上述代碼塊中進行簡化(除去冗余部分)。

static NSDateFormatter *cachedDateFormatter = nil;

+ (NSDateFormatter *)cachedDateFormatter {

// If the date formatters aren't already set up, create them and cache them for reuse.

if (!dateFormatter) {

dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setLocale:[NSLocale currentLocale]];

[dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss"];

}

return dateFormatter;

}

如果緩存了日期格式化或者是其他依賴于current locale的對象,那么我們應該監(jiān)聽NSCurrentLocaleDidChangeNotification通知,當current locale變化時及時更新被緩存的日期格式化對象。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 為什么要優(yōu)化NSDateFormatter? 首先,過度的創(chuàng)建NSDateFormatter用于NSDate與NS...
    Crazy2015閱讀 728評論 0 0
  • 為什么要優(yōu)化NSDateFormatter? 優(yōu)化方式有哪些? 為什么要優(yōu)化NSDateFormatter? 首先...
    tingxins閱讀 7,266評論 2 20
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,692評論 4 61
  • 不知道在什么時候 也不知道在哪一天 你悄悄撥動了我的心弦 奏出了一曲美秒的樂章 有一種感覺叫妙不可言 如夢似幻,幸...
    yzwjjx閱讀 131評論 0 0
  • “你我都不可能擺脫時鐘的束縛,彼此都已淪為社會這個時鐘的齒輪。一旦少了齒輪,時鐘就會出亂子??v然自己渴望率性而為,...
    SEVEN_24閱讀 1,326評論 0 2

友情鏈接更多精彩內(nèi)容