NSUserDefaults Performance Boost
Tim Johnsen / March 16, 2015
Since iOS 8 was released we’ve noticed some sluggishness when using Flipboard in the simulator. When taking a trace with Instruments in normal use we noticed a significant amount of time was being spent in CFPreferences
.
On Twitter, an Apple engineer acknowledged that there were some changes in iOS 8 that added something called cfprefsd
, and that emulating that in the simulator required synchronous reads from disk. This seemed to be the bottleneck we were encountering.
About a month ago we were talking as a team about how slow we felt our app had become to debug in the simulator, so we decided to try to do something to speed it up. Our approach was to introduce a man-in-the-middle write-through cache to NSUserDefaults
in memory. We do so by swizzling out all ofNSUserDefaults
’ setters and getters and adding a per-instanceNSMutableDictionary
to cache values. We avoid compiling this for device builds using TARGET_IPHONE_SIMULATOR
because there aren’t such performance issues on device. The increase in performance is dramatic, where we were once spending 80% of our time in CFPreferences
we’re now spending 1%.
If you’re seeing performance issues related to NSUserDefaults
in the simulator I recommend trying this out, it’s open source and available for download on GitHub. To get started using it all you need to do is include it in your project.
Please note that use of this category may cause side effects when debugging extensions. This is documented in the GitHub project.