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

funkyboy commented Jun 24, 2016

Use

CheapDateFormatter.formatter().stringFromDate( ... )

NSDateFormatter is 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?

@olegam
Copy link
Copy Markdown

olegam commented Jun 24, 2016

You could store it in the thread cache rather than a static variable. That would make it thread safe.

@jrturton
Copy link
Copy Markdown

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.

@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