Reputation: 5542
In my app I save lots of data to shared preferences. Some of these shared preferences are used many times during an app session. I was thinking of having a class which would hold the values of the most commonly used SharedPreferences
in static
members.
So if I have a City
object that is accessed many times in the app, I thought I would fetch the City
object value from SharedPreference during app start, store it in a static variable and use that value in the rest of the app (via some manager class).
But I am wondering if this would provide any performance improvements? I tried to find the performance comparisons of SharedPreferences
and Statics
but couldn't find anything that could answer my question well. Anybody has a clear answer? Thanks!
Upvotes: 2
Views: 515
Reputation: 21
I have tried both possibilities on a project that mostly read (only write once) and didn't really find any differences in performance. By the way, maybe if you access SharedPreferences more than once in the class, could be a good idea to just read the data from there.
Upvotes: 0
Reputation: 4838
Shared Preferences as you know, are stored in an XML file, so every time you modify your data, write operation on the file system is done. On the other hand, once data are read from the XML file associated with the Shared Preferences, the values are cached in memory.
So, during the execution of your application, if you only read data from Shared Preference and write data a few time, using static data or use directly Shared Preference has the same performance. If you write many time the data, you can consider to cache data on static variables and then write to Shared Preferences.
Just some final consideration:
I hope this helps.
Upvotes: 2
Reputation: 423
Shared Preferences are cached in memory (after the first read) anyway so you would not be gaining anything.
You may add subtle errors if you do not remember to write through to the SharedPreferences when updating though.
Upvotes: 1