Search code examples
javaandroidsharedpreferencesandroid-preferencespreferences

sharedPreferences apply() saves all the above or just the last one? How it works?


My question is very simple, but I did not found an answer (sorry if it is somewhere and just did not found it).

How sharedpreferences.editor.apply() works?

To be clear, I have this code for example:

MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.apply();
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();

This works in my project. But is it better regarding performance to use this above or this below?

MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();

Basically, the code above is correct?
Will it work for all the putSomething above or apply() works just for one putSomething?


Solution

  • The last one for sure. Both apply() and commit() will save all changes. Why would you even want to apply the changes multiple times? Although the last one is better for performance, you won't really notice because apply() is aSync. Yet, don't do unnecessary stuff. However commit() will decrease performance because it is not aSync.