iOS: Speed of reading NSUserDefaults vs variables

2019-04-10 01:56发布

问题:

I have an app and it calls to variables ofently. And these variables are stored in NSUserDefaults.

Im wondering where NSUserDefaults is storing? And if i call to NSUserDefaults directly instead of using to variables.

Which is faster? variables or NSUserDefaults. Because using variables to store NSUserDefaults will be the cause of using more memory.

回答1:

NSUserDefaults persists its data on disk so at some point it must load that data from disk in order to store it in memory. It will need to write it back to disk when you tell it to synchronize.

Once in memory, it will store it in a dictionary-like container (probably NSMutableDictionary).

Reading from both disk is very expensive compared to reading a variable directly and reading from a dictionary is moderately expensive compared to reading a variable.

Reading/writing variables it much quicker by a long way.



回答2:

NSUserDefaults has a different use case than variables in your code.

The data is packed into a plist representation and needs to be stored to disk (well, at least when it gets synchronized), or read from disk (or from the cache, or some other implementation detail Apple sees fit). In any case, using the defaults should typically be much slower than using a simple variable. And the bigger the user defaults get, the higher the impact, as it will most probably store/read all of it every time. If it will matter in your use case is a different question that we cannot answer.

Use the approach that suits your needs: NSUserDefault to persist settings between application launches, and variables for normal operation. There's nothing wrong with having the settings cached in a local variable and only persisting changes (maybe not every time something changes).



回答3:

If you are worried that keeping data in variables takes memory, then you should use CoreData instead. You might also consider that NSUserDefaults will take memory :-)

NSUserDefaults is persistent storage. If you use it right, the data will be there again after your app crashes. Use it for things that you want to remember when your app runs the next time. Use variables for things that can start fresh when your app starts the next time.