Reputation: 11184
Shared preferences are stored as key-value pairs inside an xml file. That's a fact. I haven't been able to find any documentation on the batter but ... when trying to find and load the value of a certain key, how does it actually look for the key inside the xml? Does it load the entire xml file into memory and then searches for the key or does it use some other method which is more memory friendly to go through each key?
I've come across an app which stores a ton of key-value pairs in shared preferences instead of using a database (there's A LOT!) and it is my hunch that this is quite memory intensive, as it will load the entire file into memory just to retrieve the specific item.
Can anyone clarify how this works "under the hood" ?
Thanks!
Upvotes: 1
Views: 296
Reputation: 1007554
Does it load the entire xml file into memory and then searches for the key...?
Yes, at least in the standard implementation. Technically, SharedPreferences
is an interface, but AFAIK SharedPreferencesImpl
is the implementation that Context
uses for methods like getSharedPreferences()
.
Upvotes: 2
Reputation: 14183
If you're curious about an implementation of SDK classes you can download the sources directly with Android Studio. You can than hold ctrl and left-click on an SDK class and jump directly into the code, or even find usages and look for classes by name. If you've never done it I would really recommend it, it's super convenient.
As for the specific question, SharedPreferencesImpl
(as pointed out by CommonsWare is the implementation of SharedPreferences
returned by Context
) only loads the file in the constructor and when the file changes. When reading values the performance should then be very close to reading directly from a HashMap
If you're writing though, it will write the entire file when you call apply
or commit
on Editor
, but using apply
will do that asynchronously.
Upvotes: 2