Issue
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!
Solution
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:
- If you have many structured data to read/write, consider to use SQLite database
- Shared Preference supports simple type. If you need to persist big class, consider using Kripton Persistence Library. Just to be clear, I'm the author of Kripton.
I hope this helps.
Answered By - xcesco
Answer Checked By - David Marino (JavaFixing Volunteer)