Skip to content

Instantly share code, notes, and snippets.

@luca-bernardi
Last active December 10, 2015 13:04
Show Gist options
  • Save luca-bernardi/4190354 to your computer and use it in GitHub Desktop.
Save luca-bernardi/4190354 to your computer and use it in GitHub Desktop.
Threadsafe NSDateFormatter's instance cache
/**
As Apple said [NSDateFormatter init] is very expensive (https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW10)
In Apple's code is used a static const, but since NSDateFormatter
isn't thread safe a better approach is to use Thread local store (http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW4)
to cache the NSDateFormatter instance
*/
NSString * const kCachedDateFormatterKey = @"CachedDateFormatterKey";
+ (NSDateFormatter *)dateFormatter
{
NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
NSDateFormatter *dateFormatter = [threadDictionary objectForKey:kCachedDateFormatterKey];
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSS"];
[threadDictionary setObject:dateFormatter forKey:kCachedDateFormatterKey];
}
return dateFormatter;
}
@robrix
Copy link

robrix commented Mar 1, 2014

_Thread_local/thread_local (depending on your compiler environment) static variables may be an acceptable alternative to the thread dictionary; they can clarify the logic quite pleasantly:

static _Thread_local NSDateFormatter *formatter;
if (!formatter) { formatter = …; }
return formatter;

@luca-bernardi
Copy link
Author

@robrix didn't know about that. Thanks for the tips!

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