I have a little doubt about the SharedPreferences in Android.
To delete a preference, we mainly have two options:
First:
SharedPreferences.Editor edit = (Editor) getSharedPreferences(Constants.APP_DEFAULT_PREF, MODE_PRIVATE).edit();
edit.putString(Constants.PREF_ACC, null);
edit.commit();
Second:
SharedPreferences.Editor edit = (Editor) getSharedPreferences(Constants.APP_DEFAULT_PREF, MODE_PRIVATE).edit();
edit.remove(Constants.PREF_ACC);
edit.commit();
In either case, fetching Constants.PREF_ACC value from SharedPreferences will return null.
I was wondering which one should I prefer. Is there any memory related issues in either of them? What will the System.gc behavior be with them?
Theoretically remove is better than put(null), because it removes both the key and value (once committed) instead of mapping (and keeping) the key to a null value.
But judging by the Android 5.1.1 implementation, they are equivalent :
...
String k = e.getKey();
Object v = e.getValue();
// "this" is the magic value for a removal mutation. In addition,
// setting a value to "null" for a given key is specified to be
// equivalent to calling remove on that key.
if (v == this || v == null) {
if (!mMap.containsKey(k)) {
continue;
}
mMap.remove(k);
} else {
...
That is also what one of the putXXX methods (putStringSet) documentation says :
Passing null for this argument is equivalent to calling remove(String) with this key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With