NSUserDefaults Performance Boost

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 1 CFPreferences . On Twitter, an Apple engineer acknowledged that there were some changes in iOS 8 that added something […]

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

1
CFPreferences

.

On Twitter, an Apple engineer acknowledged that there were some changes in iOS 8 that added something called

1
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

1
NSUserDefaults

in memory. We do so by swizzling out all of

1
NSUserDefaults

’ setters and getters and adding a per-instance

1
NSMutableDictionary

to cache values. We avoid compiling this for device builds using

1
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

1
CFPreferences

we’re now spending 1%.

If you’re seeing performance issues related to

1
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.

Source: Flipboard