Last active
June 24, 2016 18:40
-
-
Save funkyboy/625f9c3adcc65edf14cde392407b68cd to your computer and use it in GitHub Desktop.
One way to create a date formatter only once in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class CheapDateFormatter { | |
| private static let dateFormatter = NSDateFormatter() | |
| static func formatter() -> NSDateFormatter { | |
| dateFormatter.dateStyle = .MediumStyle // reconfiguring is as expensive as recreating | |
| dateFormatter.timeStyle = .ShortStyle // not good for performance. See comments below. | |
| return dateFormatter | |
| } | |
| } |
Author
You could store it in the thread cache rather than a static variable. That would make it thread safe.
They're also expensive to configure / reconfigure. I tend to go with a lazy global configured when you create it, for each format I will need in the app.
Author
@olegam as iOS7 and Mac OS 10.9 NSDateFormatter is thread safe.
Evidence of @jrturton observation: http://adcdownload.apple.com/wwdc_2012/wwdc_2012_session_pdfs/session_235__ios_app_performance_responsiveness.pdf
As much as I like the design of the class it doesn't bring the best performance :(
Setting the dateFormat / dateStyle is expensive, so you're not really saving anything by having a static reference here.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use
CheapDateFormatter.formatter().stringFromDate( ... )NSDateFormatteris notoriously expensive to create. I use this trick to create it only once.I like the fact that it's extensible so I can add more methods to return a formatter with a different combination of date/time styles.
Do you have suggestions to make this better/easier?