Ramesh Lingappa
Ramesh Lingappa

Reputation: 2488

NSDateFormatter init vs copy performance

my ios application requires heavy use of NSDateFormatter, i know that creating a instance of NSDateFormatter is expensive, however creating few singleton instances is fine, but i need to use lot of date formats , which i cannot create instance for all of these formats,

what am doing is creating an singleton NSDateFormatter with common settings like timezone , locale, and whenever i want i will clone the nsdateformatter and make change to that,

my question is

does copy is better than clone?

what would be the best practice to handle many date formats ?

Upvotes: 2

Views: 709

Answers (2)

rmaddy
rmaddy

Reputation: 318854

I can't speak to the performance issues (run your own tests to see which is faster).

But what I would do is create a dictionary of date formatters using the date format as the key.

Write a method like the following:

- (NSDateFormatter *)dateFormatterForFormat:(NSString *)dateFormat {
    NSDateFormatter *formatter = formats[dateFormat];
    if (!formatter) {
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:dateFormat];
        // any other setup needed
        formats[dateFormat] = formatter;
    }

    return formatter;
}

In the code, formats is some NSMutableDictionary ivar or static variable you setup in the class.

Upvotes: 0

Catfish_Man
Catfish_Man

Reputation: 41821

Unfortunately, the expense of date formatter setup is incurred the first time you use it after either creating it or setting any properties of it. So you won't be able to avoid the cost at least once for each configuration of formatter you use.

I have a few suggestions:

  1. Make sure that the cost actually matters before spending a lot of time on it. Do the naive, easy to get right code, and then profile it with Instruments
  2. Look at your usage patterns. Do you use a few formats far more than the rest? Consider caching those. Do you use a few at a time, then a few different ones, and so on? Consider caching a small number of recently used formatters so that you can exploit this pattern.
  3. In the worst case scenario (formatter performance does matter, and there's no pattern to how you use them), consider writing a class to manage a cache of formatters and clear them when you get a memory pressure warning. That way you can try to get the best performance possible when not running low on ram, and free up the ram when you really need it.

Upvotes: 3

Related Questions