首先,過度的建立<code>NSDateFormatter</code>用于<code>NSDate</code>與<code>NSString</code>之間轉換,會導緻App卡頓,打開Profile工具查一下性能,你會發現這種操作占CPU比例是非常高的。據官方說法,建立<code>NSDateFormatter</code>代價是比較高的,如果你使用的非常頻繁,那麼建議你緩存起來,緩存<code>NSDateFormatter</code>一定能提高效率。
Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable
即隻有在<code>UI</code>需要使用轉換結果時在進行轉換。
根據<code>NSDateFormatter</code>線程安全性,不同的iOS系統版本記憶體緩存如下:
prior to iOS 7
如果直接采用靜态變量進行存儲,那麼可能就會存線上程安全問題,在iOS 7之前,<code>NSDateFormatter</code>是非線程安全的,是以可能就會有兩條或以上的線程同時通路同一個日期格式化對象,進而導緻App崩潰。
iOS 7 or later
在iOS 7、macOS 10.9及以上系統版本,<code>NSDateFormatter</code>都是<code>線程安全</code>的,是以我們無需擔心日期格式化對象在使用過程中被另外一條線程給修改,為了提高性能,我們還可以在上述代碼塊中進行簡化(除去備援部分)。
如果緩存了日期格式化或者是其他依賴于<code>current locale</code>的對象,那麼我們應該監聽<code>NSCurrentLocaleDidChangeNotification</code>通知,當<code>current locale</code>變化時及時更新被緩存的日期格式化對象。
In theory you could use an auto-updating locale (autoupdatingCurrentLocale) to create a locale that automatically accounts for changes in the user’s locale settings. In practice this currently does not work with date formatters.
Apple Threading Programming Guide
如果時間日期格式是固定的,我們可以采用C語言中的strptime函數,這樣更加簡單高效。
}
本文轉自lzwxx 51CTO部落格,原文連結:
http://blog.51cto.com/13064681/1943390