In case you didn’t know, NSDateFormatter is SLOOOOOW

NSDateFormatter is the defacto way of turning dates into strings and strings into dates.  Unfortunately it’s also slow as molasses even with reuse and never changing the format string.  This quick tip is about using NSCalendar to handle getting dates from strings, especially in cases where you have to perform a ton of these operations (thousands) in a short amount of time.

Let’s take some dates in a format that looks like this: YYYYMMDDHHMMSS (this is a real example from some work I’ve been doing).  Also, in this case all months and days are padded with zeros such that 1/1/2010 comes across as 20100101000000.  To turn the string into a date we take the following approach:


NSString *yearString = [dateString substringWithRange:NSMakeRange(0, 4)];
NSString *monthString = [dateString substringWithRange:NSMakeRange(4, 2)];
NSString *dayString = [dateString substringWithRange:NSMakeRange(6, 2)];
NSString *hourString = [dateString substringWithRange:NSMakeRange(8, 2)];
NSString *minString = [dateString substringWithRange:NSMakeRange(10, 2)];
NSString *secString = [dateString substringWithRange:NSMakeRange(12, 2)];

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:[yearString intValue]];
[comps setMonth:[monthString intValue]];
[comps setDay:[dayString intValue]];
[comps setHour:[hourString intValue]];
[comps setMinute:[minString intValue]];
[comps setSecond:[secString intValue]];
NSDate *theDate = [[NSCalendar currentCalendar] dateFromComponents:comps];

Believe it or not the above code cut the time spent formatting dates by about 75% (looking at it through time profiler).

Advertisements

Posted on September 22, 2011, in Code and tagged , , , . Bookmark the permalink. 5 Comments.

  1. Reusing [NSCalendar currentCalendar] from a static variable seems to help even a bit more.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: