What do people mean when they say this is expensive? I create instances of a lot of transient objects just for intermediate storage (NSString and NSDate are typical ones). How do I know if my program use of NSDateFormatter is overdoing it?
Until now, I have tended to create what amounts to a singleton, but my preference would be to encapsulate it into some of the other objects it is associated with so I can use self references.
Short of running performance tests, I am looking for a better "rule-of-thumb" understanding of why I should or shouldn't do this.
I had this same question sometime ago. I've ran Instruments on some app I was working and I figure out the previous developers were creating a new NSDateFormatter for each custom log they did. Since for each screen they used to log about 3 lines. The app used to spend about one sec only creating NSDateFormatters.
The simple solution would be retain the date formatter instance in your class as an attribute or something and reuse it for each log line.
After some trivial thinking, I've came with a "factory" to handle the reuse of NSDateFormatters based on format and locale wanted. I request a date formatter of some format and locale and my class give the already loaded formatter to me. Good performance tuning, you should try.
PS: Maybe someone would like to test it, so I made it public: https://github.com/DougFischer/DFDateFormatterFactory/blob/master/README.md
When something like this is referred to as expensive, it doesn't necessarily mean that you should never do it, it just means avoid doing it in situations when you need to get out of a method as quickly as possible. For example, back when the iPhone 3G was the latest device, I was writing an application with a
UITableView
that formatted numbers for display in each cell (I might add, this was back when I was a beginner at iOS development). My first attempt was the following:The scrolling performance of this code was terrible. The frame rate dropped to about 15 FPS because I was allocating a new
NSNumberFormatter
every timetableView:cellForRowAtIndexPath:
was hit.I fixed it by changing the code to this:
The difference here is that I've lazily loaded the
NSNumberFormatter
into an ivar, so that each run oftableView:cellForRowAtIndexPath:
no longer allocates a new instance. This simple change pushed the scrolling performance back up to about 60 FPS.This specific example isn't quite as relevant anymore, as the newer chips are capable of handling the allocation without affecting scrolling performance, but it's always better to be as efficient as possible.