Md1079
Md1079

Reputation: 1360

NSUserDefaults causing performance issues

I believe I have CPU performance issues caused by overuse of NSUserDefaults. Is this possible?

I am debugging some code that has used it to store a lot of user data and now subsequent calls to store data are talking over 4 seconds per call.

What would be causing these long delays?

// Save data in user defaults
NSDate *timerStartTime = [NSDate date];

NSLog(@"Data Size %lu", (unsigned long)[result.data length]);
[self setObject:result.data forKey:defaultName];
NSTimeInterval elapsed = [[NSDate date] timeIntervalSinceDate:timerStartTime];
NSLog(@"Time For Function: %f", elapsed);

Output:

Time For Function: 4.1

Upvotes: 0

Views: 1358

Answers (1)

chrissukhram
chrissukhram

Reputation: 2967

If you are storing large amounts of data you should definitely not use NSUserDefaults to do so.

NSUserDefaults is good to use for things such as flags, simple settings or user variables such as a nickname, etc. Essentially user preferences.

This is because:

  • NSUserDefaults is loaded and saved in its entirety every time it is loaded.
  • NSUserDefaults is loaded on the application launch so you cannot thread its loading process.

Storing data should be done using Core Data: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html

Or if it is simply a Dictionary or Array of strings you can use Property Lists: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html

NSUserDefaults does use a pList to store its data so you will come across some of the same limitations but you will have more control as to when and how you will write or read your data. Also, it is not good practice to use NSUserDefaults as a make-shift DB when it has an intended purpose of preferences.

Upvotes: 4

Related Questions