Skip to content

Instantly share code, notes, and snippets.

@funkyboy
Last active June 24, 2016 18:40
Show Gist options
  • Select an option

  • Save funkyboy/625f9c3adcc65edf14cde392407b68cd to your computer and use it in GitHub Desktop.

Select an option

Save funkyboy/625f9c3adcc65edf14cde392407b68cd to your computer and use it in GitHub Desktop.
One way to create a date formatter only once in Swift
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
}
}
@funkyboy
Copy link
Copy Markdown
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 :(

@subdigital
Copy link
Copy Markdown

Setting the dateFormat / dateStyle is expensive, so you're not really saving anything by having a static reference here.

https://twitter.com/Catfish_Man/status/732982650890113024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment