0

I have a HashMap<String, Integer> which I need to save across resumes/restarts, across the activity lifecycle, when app restarts etc.
There are the following options:
1) Use shared preferences and loop over all keys and store the <key,value> pairs exactly like this in shared preferences
2) Convert the hashmap to JSON and save as a String in shared preferences.
3) Since hashmap is serializable then save it as such in internal memory.

But what is the best approach performance wise? What is the standard/best practice?
To me it seems option (3) but from various posts many people say the opposite. Is the overhead of serializable that much for my specific definition of hashmap? I.e. no complex object keys-values?

Jim
  • 17,102
  • 31
  • 115
  • 227

3 Answers3

1

Option (3). why?

1)Shared preferences use XML file to store data. You have to read file and parse the XML.(read + parse)

2)You have to read file and parse XML, then parse JSON.(read + parse + parse)

3)You just read file and initialize hashmap.(read)


Why people do not use option3?

because they want to communicate to other technologies so portability is going to be the high level requirement.

  • I see your point. But I was under the impression that people consider serialziation slow also – Jim Mar 26 '16 at 10:53
0

2) is standard and best practice.

I would consider 1) bad practice as it abuses SharedPreferences.

Regarding performance: You'd have to benchmark this tailored to your usecase. I would expect 2) to be fastest, but depending on map size and JSON conversion implementation, 3) might be faster.

Sidenote: If your map has less than 1000 entries I wouldn't worry about performance

Premature optimization is the root of all evil

— Donald Knuth

F43nd1r
  • 7,212
  • 3
  • 21
  • 50
  • Yes it should have no more than 1000 entries. Why does 1 abuses the shared preferences? JSON string would be stored there too – Jim Mar 25 '16 at 21:17
  • SharedPreferences are an "Interface for accessing and modifying preference data" and should be used to store settings or behaviour flags. – F43nd1r Mar 25 '16 at 21:21
  • Of course you can use it otherwise, and if your map isn't big this won't be a problem. Generally speaking: saving complex data in SharedPreferences might lead to performance decrease, because SharedPreferences are kept in memory. – F43nd1r Mar 25 '16 at 21:23
0

Did you consider an Application class or any singleton as a container for your data to survive configuration changes?

You can also use a retained Fragment for that purpose.

These variants are the fastest while app is running.

So save state between restarts you have to use serialisation one way or another.

Google team claims Parcelable interface is faster than classic Serializable (SO link).

Also instead JSON consider GSON (SO link).

Of course, a profiler is your final decision referee...

Community
  • 1
  • 1
Maxim G
  • 1,489
  • 1
  • 13
  • 23